Advertise here: Contact FM.


Preloading images.
November 14, 2006 8:00 AM   RSS feed for this thread 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 comments 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 What kind of treatment have yo...   |   What is my life purpose? Am I... Newer »
This thread is closed to new comments.


Related Questions
Linux distro or software for full-screen kiosk... July 29, 2008
How to make spreadsheet dynamically sortable web... April 26, 2008
How do I legitimately hijack website content? August 15, 2007
I forgot HTML, I forgot CSS April 22, 2007
Recommend a javascript for rotating images November 21, 2005