Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Can I sync up multiple image onload calls? Re: Can I sync up multiple image onload calls?

#93673
Mottie
Member

Hi Noah!

Actually recently blogged a snippet of code/mini plugin that basically does this.

Here is the code:

/*
Check if all images are loaded
- Callback occurs when all images are loaded
- image load errors are ignored (complete will be true)
- Use:
$('.wrap img').imagesLoaded(function(){
alert('all images loaded');
});
*/

jQuery.fn.extend({
imagesLoaded: function( callback ) {
var i, c = true, t = this, l = t.length;
for ( i = 0; i < l; i++ ) {
if (this.tagName === "IMG") {
c = (c && this
.complete && this.height !== 0);
}
}
if (c) {
if (typeof callback === "function") { callback(); }
} else {
setTimeout(function(){
jQuery(t).imagesLoaded( callback );
}, 200);
}
}
});

If you use $(window).load(){ /* code here */ }); then you already know all images are loaded. But if you lazy load or add more images after the page has loaded, this is an alternative method.

Here is how to use it to run the callback after multiple images have finished loading:

$(function(){
$('.wrap img').imagesLoaded(function(){
alert('all images loaded');
});
});

Or, if you only have one image, just target that image

$('img#fred').imagesLoaded(function(){
alert('Fred!');
});

If there are no images in your selector, it automatically runs the callback by default.