Skip to content

Instantly share code, notes, and snippets.

@greypants
Created July 25, 2012 21:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greypants/3178658 to your computer and use it in GitHub Desktop.
Save greypants/3178658 to your computer and use it in GitHub Desktop.
JS: Preload a set of images and fire a callback when all are loaded.
var preloadImages = function(imageSources, callback) {
var images = [];
var tryCallback = function() {
var allImagesLoaded = (function(){
for (var i = images.length; i--;) {
if(!images[i].isLoaded){
return false;
}
}
return true;
})();
if(allImagesLoaded) {
callback();
}
};
for (var i = imageSources.length; i--;) {
var imageSrc = imageSources[i];
var image = document.createElement('img');
images.push(image);
image.onload = function() {
this.isLoaded = true;
tryCallback();
};
image.src = imageSrc;
}
};
var callback = function() {
console.log('OHHAI!')
};
preloadImages([
'http://placekitten.com/1000/1000',
'http://placekitten.com/300/1000',
'http://placekitten.com/1000/2000'
], callback);
@aradalvand
Copy link

asdfadfasdf

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