Skip to content

Instantly share code, notes, and snippets.

@juanbrujo
Created October 15, 2013 22:44
Show Gist options
  • Save juanbrujo/6999820 to your computer and use it in GitHub Desktop.
Save juanbrujo/6999820 to your computer and use it in GitHub Desktop.
jQuery: preloads an array of images. Demo: http://codepen.io/juanbrujo/pen/yIiCs
(function($) {
var imgList = [];
$.extend({
preload: function(imgArr, option) {
var setting = $.extend({
init: function(loaded, total) {},
loaded: function(img, loaded, total) {},
loaded_all: function(loaded, total) {}
}, option);
var total = imgArr.length;
var loaded = 0;
setting.init(0, total);
for(var i in imgArr) {
imgList.push($("<img />")
.attr("src", imgArr[i])
.load(function() {
loaded++;
setting.loaded(this, loaded, total);
if(loaded == total) {
setting.loaded_all(loaded, total);
}
})
);
}
}
});
$.preload(
["http://www.lib.utexas.edu/maps/world_maps/world_pol495.jpg","http://www.lib.utexas.edu/maps/world_maps/time_95.jpg","http://www.jimmymack.org/images/world_map.gif","http://www.nationsonline.org/maps/political_world_map3000.jpg"],
{
init: function(loaded, total) {
$('body').html("Loading "+loaded+" of "+total+" images");
},
loaded: function(img, loaded, total) {
$('body').html("Loading "+loaded+" of "+total+" images");
},
loaded_all: function(loaded, total) {
$('body').html("&#9786; all loaded").addClass('loaded');
}
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment