Skip to content

Instantly share code, notes, and snippets.

@robotlolita
Created September 19, 2010 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robotlolita/586988 to your computer and use it in GitHub Desktop.
Save robotlolita/586988 to your computer and use it in GitHub Desktop.
/**
* preload(urls[, wait=10][, callback])
* - urls (Array): a list of all image urls to preload
* - delay (Number): how much time to wait for an image before
* flagging it as unreachable, in seconds.
* - callback (Function): optional function to call after all images
* are preloaded.
**/
function preload(urls, wait, callback) {
var timer_id; // id of the last timer event
if (typeof wait == "function") {
callback = wait;
wait = 10 }
// signals the previous item was loaded and continues to load the
// next items
function next() {
var current, img;
clearTimeout(timer_id);
current = urls.shift();
if (current) { // there are sill items to load
img = new Image();
img.onload = next;
img.src = current;
// if it's not loaded in 10 seconds, forget about it. It
// maybe just because the image is just too large, or any
// other thing, and the image may be loaded later on. But
// since the Image object doesn't offers an `onerror`
// event, we have to make sure an unreachable image won't
// block the entire queue.
timer_id = setTimeout(next, wait * 1000) }
else { // all items loaded
callback && callback();
}
}
next();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment