Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Image Preloader?

Status
Not open for further replies.

MrMiyagi

Technical User
Feb 11, 2009
43
FI
Hi,

I have this code for preloading some big images on my page. The idea is to show a loading animation until the pics in the array are loaded. Most of the time it works, but sometimes it quits the loading animation before all images are loaded.

Would be great if some jscript guru could check out the code and suggest improvements to make it better...All tips are very welcome. Thanks.

The code:


// First the array for the pics that need to be loaded //before the page can be viewed:

var picSrc=new Array(4);

picSrc[0] = 'img/pic1.jpg';
picSrc[1] = 'img/pic2.jpg';
picSrc[2] = 'img/pic3.jpg';
picSrc[3] = 'img/pic4.jpg';



function initPics(){
var ImagePreLoader = Class.create({
callback: null,
imageCache: new Array,
loaded: 0,
processed: 0,
noOfImages: 4,
initialize: function(images, options) {
if (options) {
if (options.callback) this.callback = options.callback;
}

this.noOfImages = images.length;
for ( var i = 0; i < images.length; i++ )
this.preload(images);
},
preload: function(imgSrc) {
var image = new Image;
this.imageCache.push(image);
Event.observe(image, 'load', this.onload.bindAsEventListener(this), false);

Event.observe(image, 'error', this.onerror.bindAsEventListener(this), false);

Event.observe(image, 'abort', this.onabort.bindAsEventListener(this), false);
image.preloader = this;
image.loaded = false;
image.src = imgSrc;
},
onComplete: function() {
this.processed++;
if (this.processed==this.noOfImages) {
this.callback(this.imageCache, this.loaded);
}
},
onload: function(e) {
this.loaded++;
this.onComplete();
},
onerror: function(e) {
this.onComplete();
},
onabort: function(e) {
this.onComplete();
}
});





var imgPreloadCallback = function(imageCache, loaded) {

// imageCache is an array of the loaded images
//loaded is an int of the number of images that loaded.
//doSomethingAfterImagesAreLoaded();
picsPreLoaded = true;
}

var imgLoader = new ImagePreLoader(picSrc,{callback:imgPreloadCallback});

}

 
I have used a simpler preload function for years:
Code:
var preimages = new Array();
function imgpreload(imgarray)
{
for (var ii = 0; ii < imgarray.length; ii++)
  {
  preimages[ii] = new Image();
  preimages[ii].src = imgarray[ii];
  }
}

imgpreload(picSrc);

Lee
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top