var img = document.getElementById('bgimg');
img.onload = function() {
  var ratio = document.body.offsetWidth / img.width;
  if (ratio < 1) {
    img.height = img.height * ratio;
    img.width = img.width * ratio;
  }
}

