Created
February 5, 2014 08:49
-
-
Save kamilogorek/8819542 to your computer and use it in GitHub Desktop.
Wait for all images to load before executing callback
This file contains 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
'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; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.