Rob Gonda's Blog

HTML OnMissingImage

Scenario: you need to display a bunch of images but you're not 100% certain that they exist.

Solution 1: If the images are hosted in the same server you can loop over their physical path display an alternate image if the image was not found on disk. This solution is very taxing (I/O intensive) and not efficient at all. It also won't work if you're not hosting the images.

Solution 2: What now? I found a few JavaScripts to loop over every image found in the DOM and check of http status, then replace them if the image wasn't loaded properly. This solution is much better because it's decentralized and the load is delegated to the client as opposed of the server, and it also works with images hosted elsewhere.

Solution 3 (winner): Did you know that the image tags have an onError attribute? I can't believe that after 15 years of web development I just found out about this now :) ... This is the optimal solution as it is native to the browser, works on every browser (I tested IE6+, FF2.0+, Safari1.3+, all on Mac and PC).

Check it out, I included two images: img01.gif, which exists on my server, and img02.gif. Both of them have an onerror attribute with a simple script: this.src=error.gif.

img02.gif does not exist on my server, consequently the script will be executed and load my error.gif

<img src="img01.gif" width="100" height="100" onerror="this.src='error.gif';">
<br clear="all">
<img src="img02.gif" width="100" height="100" onerror="this.src='error.gif';">



So simple and yet so powerful. Enjoy.

TrackBacks
There are no trackbacks for this entry.

Trackback URL for this entry:
http://www.robgonda.com/blog/trackback.cfm?6F36F871-B332-AF2B-5E6B823579B1F028

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
This blog is running version 5.9.003. Contact Blog Owner