Skip to content

Instantly share code, notes, and snippets.

@ray-peters
Last active September 10, 2015 22:29
Show Gist options
  • Save ray-peters/2315f4a4e2117434242d to your computer and use it in GitHub Desktop.
Save ray-peters/2315f4a4e2117434242d to your computer and use it in GitHub Desktop.
Emits an event when all the images have finished loading
$( document ).ready( function(){
// Interesting thing happens when you have so many images on the page.
// Count them and wait for every onload event to fire.
var $images = $( "img" ),
imagesLoadedHandler = function(){
var totalImagesToLoad = $images.length,
imageLoadedCount = 0;
return function(){
if ( ++imageLoadedCount === totalImagesToLoad ) {
$( window ).trigger( "allImagesLoadComplete" );
}
};
}();
for ( var i = 0, l = $images.length, imageElem; i < l; ++i ) {
imageElem = $images.get( i );
if ( imageElem.clientWidth === 0 ) {
// Image isn't loaded, wait for the onload event to fire
imageElem.onload = imageElem.onerror = imagesLoadedHandler;
} else {
// Image is already loaded
imagesLoadedHandler();
}
}
$( window ).on( "allImagesLoadComplete", function(){
alert( "ALL THE IMAGES ARE DONE LOADING! HOOORAY" );
} );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment