0

Is it possible to delay the page rendering until the images are downloaded to prevent the images from loading in as the page is being painted?

Cheers!

Aaron Benjamin
  • 1,291
  • 3
  • 18
  • 27

2 Answers2

2

You can use onload on your image to detect when it is loaded.

var img = new Image();
img.src = "http://www.mind-coder.com/example.jpg";
img.onload = function() { alert("Height: " + this.height); }

Full example below, what does it do:

  • A div called cover, covers your page before all images are downloaded (maybe showing a message like please loading).

  • The JS script (vanilla no jQuery is needed here) searchs for all the images in the page and load them using src path stored in data-src for each image.

  • onload executes when the image is loaded and loadCount variable keep track of how many images are loaded an checks for the total number in the page.

  • When the number of images loaded are the same of the images in the page, hides the cover and it shows your page.

(function() {
  var loadCount = 0;
  var imgs = document.querySelectorAll('img');
  imgs.forEach(function(img) {
img.src = img.dataset.src;
img.onload = function() {
  loadCount++;
  if (loadCount === imgs.length) {
    document.getElementById('cover').style.display = 'none';
  }
};
  });
})()
#cover {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: red;
}
<div id="cover">cover - loading</div>
<img data-src="https://upload.wikimedia.org/wikipedia/commons/d/d9/Big_Bear_Valley,_California.jpg">
<img data-src="https://upload.wikimedia.org/wikipedia/commons/9/92/Big_Sur_Coast_California.JPG">
GibboK
  • 71,848
  • 143
  • 435
  • 658
  • 1
    What if one of the images doesn't load at all (bad URL or something)? – nnnnnn Oct 04 '16 at 05:15
  • @nnnnnn thanks for commenting good point (+1), this script shows just the basic concept as OP did not specify that scenario. By the way, it is possible to detect if there a problem with an image loading using `img.onerror` and decide there what to do, example: showing an error message, or showing the page even if one page or more did not load successfully (but I as I sad depends of the OP's use case). – GibboK Oct 04 '16 at 05:20
1

You can do something like below. First set the display:none to your body in html so it will not display anything and then in the below condition

$(window).on("load", function() {
    //show the body like below
     $("body").fadeIn(500);
});

body { display: none; }

snit80
  • 623
  • 7
  • 13
  • 1
    This is nice and simple, and I'd vote for it if the OP had put the "jQuery" tag on their question... – nnnnnn Oct 04 '16 at 05:16