Skip to content

Instantly share code, notes, and snippets.

@nilegfx-snippets
Forked from html/gist:1698093
Created March 7, 2012 11:44
Show Gist options
  • Save nilegfx-snippets/1992675 to your computer and use it in GitHub Desktop.
Save nilegfx-snippets/1992675 to your computer and use it in GitHub Desktop.
Sequential images loading with jquery
function eachStep(collection, callback, endcallback){
if(collection.length == 0){
return endcallback && endcallback();
}
jQuery.when(callback(collection[0])).always(function(){
eachStep(collection.slice(1), callback, endcallback);
});
}
function loadImage(imageSrc) {
var deferred = jQuery.Deferred();
if (typeof loadImageCache[imageSrc] === "undefined") {
preloader = new Image();
preloader.onload = function() {
//console && console.log("Loaded image " + this.src);
deferred.resolve(this.src)
};
preloader.onerror = function() {
console && console.log("Can not load an image " + this.src);
deferred.reject(this.src)
};
preloader.src = imageSrc;
loadImageCache[imageSrc] = true;
}else{
console && console.log("Image cached " + imageSrc);
deferred.resolve(imageSrc);
}
return deferred;
};
function getImages(collection, callback){
eachStep(collection, function(src){
//console && console.log("Trying to preload image " + src);
return loadImage(src);
}, function(){
console && console.log("Done preloading");
callback();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment