Skip to content

Instantly share code, notes, and snippets.

@kamilogorek
Created February 5, 2014 08:49
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kamilogorek/8819542 to your computer and use it in GitHub Desktop.
Save kamilogorek/8819542 to your computer and use it in GitHub Desktop.
Wait for all images to load before executing callback
'use strict';
module.exports = function (element, callback) {
var allImgsLength = 0;
var allImgsLoaded = 0;
var allImgs = [];
var filtered = Array.prototype.filter.call(element.querySelectorAll('img'), function (item) {
if (item.src === '') {
return false;
}
// Firefox's `complete` property will always be `true` even if the image has not been downloaded.
// Doing it this way works in Firefox.
var img = new Image();
img.src = item.src;
return !img.complete;
});
filtered.forEach(function (item) {
allImgs.push({
src: item.src,
element: item
});
});
allImgsLength = allImgs.length;
allImgsLoaded = 0;
// If no images found, don't bother.
if (allImgsLength === 0) {
callback.call(element);
}
allImgs.forEach(function (img) {
var image = new Image();
// Handle the image loading and error with the same callback.
image.addEventListener('load', function () {
allImgsLoaded++;
if (allImgsLoaded === allImgsLength) {
callback.call(element);
return false;
}
});
image.src = img.src;
});
};
@ezluci
Copy link

ezluci commented Jul 12, 2021

In short terms, you need to set a counter. When an image has been loaded (line 39), increase that counter (line 40).
And you also check that counter when it equals with how many images you do have.

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