Last active
October 13, 2015 02:28
-
-
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.
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
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 ); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.