Skip to content

Instantly share code, notes, and snippets.

@MatthaeusHarris
Last active October 21, 2015 21:27
Show Gist options
  • Save MatthaeusHarris/099a2c3d622619bed6d2 to your computer and use it in GitHub Desktop.
Save MatthaeusHarris/099a2c3d622619bed6d2 to your computer and use it in GitHub Desktop.
Javascript Preloader
function preload(urls, callback) {
console.log("Setting up preload");
// Container for the actual images
var images = [];
// List of images already loaded
var loaded = {};
// Initialize loaded array to all false
for (var i in urls) {
loaded[urls[i]] = false;
}
// Function to return a customized callback based on the url
var accumulatorFactory = function(url) {
console.log("Creating accumulator for " + url);
return (function() {
console.log("Accumulator for " + url + " called");
console.log(loaded);
loaded[url] = true;
for (var i in loaded) {
if (!loaded[i]) {
// If this line is reached, we still have an image that hasn't been
// loaded. Abort this callback here.
console.log("Aborting load check because " + i + " hasn't loaded yet.");
return;
}
}
// If this line is reached, then all the images have been loaded.
console.log("All images loaded. Calling callback.");
callback();
});
}
// Actually preload the images
for (var i in urls) {
images[i] = new Image();
// Be sure to set the handler before setting the source so you don't miss the
// onload event if the image is already cached.
images[i].onload = accumulatorFactory(urls[i]);
images[i].src = urls[i];
console.log("Queued preload for " + urls[i]);
}
}
preload(['1.jpg', 'img/2.jpg', '3.gif'], function() {
// Code to start animation here
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment