Skip to content

Instantly share code, notes, and snippets.

@rexmondo
Last active August 29, 2015 14:25
Show Gist options
  • Save rexmondo/e2376e819a641ac14375 to your computer and use it in GitHub Desktop.
Save rexmondo/e2376e819a641ac14375 to your computer and use it in GitHub Desktop.
jQuery.preloadPreload images using the promise patter
/**
* jQuery.preload
*
* Preload images using the promise pattern.
*
* Usage:
*
* $.preload(img_uri, img_uri, ...).done(function(img, img, ...) {
* // Do stuff with the arguments
* });
*
* Since $.preload returns a jQuery.Deferred[1] promise, you can attach
* callbacks the same way you'll attach them to an AJAX request
*
* If you preload multiple images the script will wait until all of them are
* loaded usign $.when.
*
* [1]: http://api.jquery.com/category/deferred-object/
*/
;(function($, window, undefined) {
"use strict";
/**
* Image preloader
* @return {jQuery.Deferred.promise}
*/
$.preload = function() {
var images = arguments.length > 1 ? Array.prototype.slice.call(arguments) : arguments[0];
// Use $.when to recursively preload multiple images
if ($.isArray(images)) {
return $.when.apply(window, $.map(images, function(image) { return $.preload(image); }) );
}
// Single image
var def = $.Deferred();
var img = new Image();
img.onload = function() {
def.resolve(img);
};
img.onerror = function() {
def.reject(img);
};
img.src = images;
return def.promise();
};
})(jQuery, window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment