Last active
October 21, 2015 21:27
-
-
Save MatthaeusHarris/099a2c3d622619bed6d2 to your computer and use it in GitHub Desktop.
Javascript Preloader
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
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