Skip to content

Instantly share code, notes, and snippets.

@notthetup
Last active October 13, 2015 02:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save notthetup/4125487 to your computer and use it in GitHub Desktop.
Save notthetup/4125487 to your computer and use it in GitHub Desktop.
Javascript to run a given function only when all the images in the page are loaded.
function runOnImgLoadComplete(onImgLoadCompleteCallback){
var allImgs = document.images;
numTotalImages = imgs.length,
numLoadedImages = 0;
[].forEach.call( allImgs, function( img ) {
if (img.complete){
numLoadedImages++;
if (numLoadedImages == numLoadedImages)
onImgLoadCompleteCallback();
}
else{
img.addEventListener( 'load', function () {
numLoadedImages++;
if (numLoadedImages == numLoadedImages)
onImgLoadCompleteCallback();
}, false );
}
});
}
@notthetup
Copy link
Author

The issue with the current implementation is that if there are any images added to the DOM AFTER this function is called using AJAX calls, then this won't wait for those to load before calling the onImgLoadCompleteCallback.

The solution to that is to keep a list of all images which have the callback added and then re-enumerate all the images every time the callback is called, adding onLoad events to all the new images. But even this isn't a full solution as there is an edge case of when the new images callbacks won't be called.

AFAIK. There is no simple way to extend this to AJAX loading of images. So for now it's only in cases where all the images are in the DOM, or when the AJAX calls for loading images have already been triggered.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment