Skip to content

Instantly share code, notes, and snippets.

@html
Created January 29, 2012 09:56
Show Gist options
  • Save html/1698093 to your computer and use it in GitHub Desktop.
Save html/1698093 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();
});
}
@html
Copy link
Author

html commented Jan 2, 2013

this code is used in https://github.com/html/jquery-seq

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment