Skip to content

Instantly share code, notes, and snippets.

@andrewvc
Created March 16, 2010 23:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewvc/334688 to your computer and use it in GitHub Desktop.
Save andrewvc/334688 to your computer and use it in GitHub Desktop.
JS Single Request Image Preloader
//Preload images one at a time
(function($) {
$.sPreLoad = {
loaded: new Array, //Images that have been loaded
loading: null, //Image currently loading
unloaded: new Array, //Images not yet loaded
run: function () {
//Load all the arguments into unloaded
$(arguments).each(function(i,url) {
$.sPreLoad.unloaded.push(url);
});
//Load the first image from unloaded, wait till its done loading,
//then load another
$.sPreLoad.interval = setInterval(function() {
var loading = $.sPreLoad.loading;
if(loading && loading.complete) {
$.sPreLoad.loaded.push(loading);
$.sPreLoad.loading = null;
}
else {
var unloadedCount = $.sPreLoad.unloaded.length;
if (! loading && unloadedCount > 0) {
var newImage = document.createElement('img');
newImage.src = $.sPreLoad.unloaded.shift();
$.sPreLoad.loading = newImage;
}
else if (unloadedCount == 0) {
clearInterval($.sPreLoad.interval)
}
}
}, 100);
}
}
})(jQuery)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment