Last active
September 10, 2015 22:29
-
-
Save ray-peters/2315f4a4e2117434242d to your computer and use it in GitHub Desktop.
Emits an event when all the images have finished loading
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$( 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