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!
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!
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">
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; }