Preloading images.
November 14, 2006 8:00 AM   Subscribe

How to wait until images being preloaded by JavaScript Image objects are complete?

I have X number of thumbnails and I would like to wait until they are all loaded in full before I make the page visible. Each JavaScript Image object comes with a imgObj.complete boolean which becomes true when the entire image is loaded. I cannot simply put this in a while loop and wait because JavaScript is single-threaded. The image objects also come with an onload event that is supposed to be triggered when the entire image has been loaded, however this is not the case. Often the event is triggered without the entire image being loaded. Solutions to this problem are graciously welcome. Thank you.
posted by hcastro to Computers & Internet (3 answers total)
 
I cannot simply put this in a while loop and wait because JavaScript is single-threaded.

Well, you could use setTimeout to check asynchronously whether the image is loaded every half-second or so. But that's kind of a hack.

The image objects also come with an onload event that is supposed to be triggered when the entire image has been loaded, however this is not the case.

The onload event on images has worked for me. What do you mean by "loaded," and on which browsers is it not performing as expected?
posted by IshmaelGraves at 8:17 AM on November 14, 2006


yeah, I would use the onload event. This isn't great code, but might work for you:

var i;
var imgArray=new Array();
var numLoaded=0;

for (i=0;i<X;i++) {
     imgArray[i] = new Image();
     imgArray[i].onload = function() {
          numLoaded++;
          if(numLoaded==X) {
               doNextTask();
          }
     }
     img.='http://example.com/'+X+'.jpg';
}

posted by rajbot at 9:01 AM on November 14, 2006


Well it seems that the .onload event works fine in Firefox & Internet Explorer. I must have been implementing it wrong before. I appreciate your help.
posted by hcastro at 10:39 AM on November 14, 2006


« Older Please help me silence my nosy relatives and...   |   life purpose frustrations Newer »
This thread is closed to new comments.