Created
July 25, 2012 21:01
-
-
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.
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
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
asdfadfasdf