March 20, 2015

Wait for images to load before doing anything…

I recently had issues when trying to print elements from a freshly generated page. The page was generated via a JSON array, so we weren’t actually dealing with AJAX loads. The problem came up when I tried to print the page, the images weren’t printing, as the “window.print();” command was being fired before everything was ready. So, this is a little script to look for the total amount of images on the page, check which ones are already loaded, and wait for the remainder of images to be loaded before firing the print command.

A really cool thing to note is you can access a sorts of “properties” for the images, that I didn’t even know existed. In this case I’m looking for the boolean value of the “complete” property of the image. This (as near as I can tell) is but one of a larger set of baked-in properties most DOM elements have.

MIND = BLOWN.

[pastacode lang=”javascript” message=”Elements Loaded function” highlight=”” provider=”manual”]

var totalImages = $('body').find('img').length;
var imageCounter = 0;
console.log('Total Images: '+totalImages);
$('body').find('img').each(function(){
// CHECK TO SEE IF IMAGE IS CURRENTLY LOADED
if($(this).prop('complete')){
imageCounter++
}else{
// FIRE THE IMAGE COUNTER AND VALIDATE PAGE STATE WHEN IMAGE LOADS
$(this).load(function(){
imageCounter++;
console.log('Images Loaded: '+imageCounter);
if(imageCounter == totalImages){
window.print();
}
});
}
});

[/pastacode]

I can also see this having applications for Lazyload style galleries and dynamically generated content that doesn’t jump all over the place as images come into place. You could wait to load the images then display the completed result by fading in, making a much cleaner experience.