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:

<script language="JavaScript" type="text/javascript">
function ImgError(source){
	source.src = "/images/noimage.gif";
	source.onerror = "";
	return true;
<div><img src=""
border="1" height="100" alt="image" onerror="ImgError(this)" /></div>

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

6 thoughts on “Detecting Broken Images in JavaScript

  1. Dear Casey,

    Thanks so much for posting this article, I need a way to have error handling on our ecommerce sites. Due to product updates sometimes users of the product sheets have made spelling errors and messing the layout of our site on occation. The javascript version of this is what I used, and it works in IE 7 and Mozilla.

    Thanks for the very useful script.

    Best wishes,
    Domain Admin

  2. Pingback: Building a Datafeed Site – Step 3 | Eric Nagel

  3. Heres another way to reduce html size.

    function imgError(img){
    img.src= “placeholder_small.gif”;

    then you can call it on your imgs like such:

    <img onerror="imgError(this);" …

Comments are closed.