Skip to content

Instantly share code, notes, and snippets.

@raihan-uddin
Forked from benedict-w/jquery_image_preload.js
Created February 24, 2020 03:58
Show Gist options
  • Save raihan-uddin/c48c4687eae59b153f246373a3d0bba9 to your computer and use it in GitHub Desktop.
Save raihan-uddin/c48c4687eae59b153f246373a3d0bba9 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