Automatic JS Broken Image Replacement

It’s a sad fact of life, but sometimes webpages have broken images. Wouldn’t it be nice if there were an easy way of automatically replacing these broken images?

for (i = 0; i < document.images.length; i++) {
  var img = document.images[i];
  img.onerror = function (evt) {
    this.src = "broken-image.gif";
  }
};

This snippet of JavaScript will find all your images and replace the broken ones with broken-image.gif. Pretty spiffy, huh?

You can also do something like this to apply it to individual images:

<img src="good-image.gif" onerror="this.src='broken-image.gif';">

2 comments

  1. just one word: thanks!

  2. I found this somewhere else. It takes the idea further:

    function replaceImage(ref,img1,img2)
    {
    ref.onerror=new Function(“this.onerror=null;this.src='”+ img2 +”‘”);
    ref.src=img1;
    }

Leave a Reply to d Cancel reply

Your email address will not be published. Required fields are marked *