Skip to content

Instantly share code, notes, and snippets.

@benedict-w
Last active February 24, 2020 04:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save benedict-w/4702067 to your computer and use it in GitHub Desktop.
Save benedict-w/4702067 to your computer and use it in GitHub Desktop.
Simple jQuery Image Preload Extension
/**
* Simple jQuery Image Preloader Extension
*
* @param images = array source images to preload
* @param callback = optional function to execute when loaded
*/
$.fn.imagePreloader = function (images, callback) {
var deferreds = [];
$.each(images, function(i, src) {
deferreds.push(new $.Deferred(function (dfd) {
var image = new Image();
image.onload = function () {
dfd.resolve(image);
};
image.onerror = function () {
dfd.resolve();
};
image.src = src;
}).promise());
});
$.when.apply($, deferreds).then(function() {
if (callback) {
callback();
}
$(this).trigger('images_loaded');
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment