Detecting Broken Images in JavaScript

We’ve become accustomed to link rot and broken images in nearly all corners of the web, but is there a way to keep things a bit cleaner?

K.T. Lam of Hong Kong University of Science and Technology came up with this sweet trick using jQuery and readyState to find and replace broken images:

``` jQuery('span#gbs_'+info.bib_key).parents('ul').find('img.bookjacket[@readyState*="uninitialized"]').replaceWith('<img src="'+info.thumbnail_url+'" alt="'+strTitle+'" height="140" width="88" />'); ```

And it works really well, but only in IE. Testing for img.complete or img.naturalWidth might be possibilities, but I’m much more interested in the onerror property of the img tag:

``` <img src="picture1.gif" onerror="this.onerror=null;this.src='missing.gif';"/> ```

Or in JS:

``` var imgsrc = 'picture1.gif'; var img = new Image();   img.onerror = function (evt){ alert(this.src + " can't be loaded."); } img.onload = function (evt){ alert(this.src + " is loaded."); }   img.src = imgsrc; ```

Or call a JS function when the browser detects a broken image:

``` <html> <head> <script language="JavaScript" type="text/javascript"> function ImgError(source){ source.src = "/images/noimage.gif"; source.onerror = ""; return true; } </script> </head>   <body> <div><img src="http://jquery.com/images/bibeault_cover150A.jpg" border="1" height="100" alt="image" onerror="ImgError(this)" /></div> </body> </html> ```

I haven’t tested any of this code, but it’s just a matter of time.