Created
February 16, 2011 23:38
-
-
Save adamesque/830561 to your computer and use it in GitHub Desktop.
Uses jQuery's new Deferred object to help with image loading
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
/** | |
* 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(); | |
} |
You're welcome!
I just updated the Gist; I hadn't realized the formatting had gotten so mangled. It should be (slightly) more readable now.
Thanks!
Adam
…On Mar 24, 2011, at 12:21 PM, fcalderan wrote:
Thank you, really interesting (and practical) example using deferred =)
##
Reply to this email directly or view it on GitHub:
https://gist.github.com/830561
would be great, but the whenArray plugin seems to be no longer available
If there's an error loading the image shouldn't it reject
the deferred?
please add a usage sample
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you, really interesting (and practical) example using deferred =)