Skip to content

Instantly share code, notes, and snippets.

@avhm
Created March 25, 2011 11:29
Show Gist options
  • Save avhm/886717 to your computer and use it in GitHub Desktop.
Save avhm/886717 to your computer and use it in GitHub Desktop.
A javascript image preloader
preloader: {
// The element to update on loading progress
$progressBar: $('#loadingbar').find('span'),
// The wrapper for the loading overlay
$loadingBlock: $('#loading'),
init: function(){
this.load();
this.checkForLoad();
},
preloadArray: [
'../images/asd.png',
'../images/skasdy2.png',
'../images/asdasdad.png',
'../images/asdasdasda.jpg',
'../images/asd.png',
],
// will be filled with loading images
loadingImages: [],
// holds our timer ref
timer: null,
load: function(image){
for(i in this.preloadArray){
var newLoading = new Image();
newLoading.src = this.preloadArray[i];
this.loadingImages.push(newLoading)
}
},
checkForLoad: function(){
_self = this;
this.timer = setInterval(function(){
var loadedCount = 0,
icl = _self.loadingImages.length;
while(icl--){
if (_self.loadingImages[icl].complete)
loadedCount++;
}
// Update the loader progess
_self.updateProgress(loadedCount, _self.loadingImages.length);
if(loadedCount >= _self.loadingImages.length){
clearInterval(_self.timer);
_self.loadComplete();
}
}, 100)
},
updateProgress: function(loaded, totalToLoad){
var loadPercent = (100/totalToLoad) * loaded
this.$progressBar[0].style.width = ~~loadPercent + '%';
},
loadComplete: function(){
// init when loaded
// Do something here when all is loaded!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment