DonalOBrien.net
JavaScript in Safari revisited
11 April 2007 13:43
Dale Newfield pointed out a possible problem with approach I outlined previously for checking whether an image is completely loaded in Safari.

The problem is, if the image is loaded before the isImageLoaded() function is called for the first time (such as if it's loaded from the browser's cache), then the function always returns false, because the "completed" attribute never gets set as the image's onLoad function isn't called.

The solution, if you're creating the image element using the DOM methods in JavaScript is to set the onLoad handler before setting the src attribute. Fine! However, this won't work if you need to check an image created using HTML (say in the original document before you modify it using JavaScript). Therefore, you can use the following HTML to ensure that the attribute is set immmediately:

<img src="foo.png" completed="false" onload="this.setAttribute('completed', true)">

You can then use the same function to check if this image is fully loaded. For example, if you set these on all of your <img> elements, use this code to check if all images are loaded:

 var imgs = document.images;
 var allLoaded = true;
 do {
   for (i=0; i<imgs.length; i++) {
     if (!isImgLoaded(imgs[i]))
       allLoaded = false;
   }
 } while (!allLoaded);