Created
March 16, 2010 23:56
-
-
Save andrewvc/334688 to your computer and use it in GitHub Desktop.
JS Single Request Image Preloader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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