Skip to content

Instantly share code, notes, and snippets.

@jaredwilli
Forked from adamesque/preloader.js
Created May 7, 2011 19:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jaredwilli/960752 to your computer and use it in GitHub Desktop.
Save jaredwilli/960752 to your computer and use it in GitHub Desktop.
Uses jQuery's new Deferred object to help with image loading
/**
* Helper function for passing arrays of promises to $.when
*/
jQuery.whenArray = function ( array ) {
return jQuery.when.apply( this, array );
};
/**
* Accepts a single image src or an array of image srcs.
* @return Promise that resolves once images have loaded.
*/
function preloadImages (srcs) {
var dfd = $.Deferred(),
promises = [],
img,
l,
p;
if (!$.isArray(srcs)) {
srcs = [srcs];
}
l = srcs.length;
for (var i = 0; i < l; i++) {
p = $.Deferred();
img = $("<img />");
img.load(p.resolve);
img.error(p.resolve);
promises.push(p);
img.get(0).src = srcs[i];
}
$.whenArray(promises).done(dfd.resolve);
return dfd.promise();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment