We can use the onerror event of an img tag to load an alternate image if the main image is not found. Something like this :-

<img src="my_image.jpg" onerror="this.src='offline.jpg'" />

The above HTML code tries to load my_image.jpg and if not found, loads offline.jpg as an alternate. This is pretty good because this means you don’t have to do any server-side checks for file existence which can be really heavy if there are 50+ or so images on the page. This is all good, except that this code wont be treated as valid XHTML. Apparently, onerror is deprecated. So, what to do?

The solution is to not use onerror in the <img> tag but to add the onerror event to the <img> via Javascript.  And jQuery is the best option I think for this job. Here is what I came up with :-


// wait for page to load
$(document).ready(function() {
// add fixBroken code to all images on the document
$('img').fixBroken();
});

$.fn.fixBroken = function(){
return this.each(function(){
var tag = $(this);
var alt_img = 'offline.jpg';
tag.error(function() { // this adds the onerror event to images
tag.attr("src",alt_img); // change the src attribute of the image
return true;
} );
});
};

This code only runs after the page has loaded and adds the onerror event to all img tags on the document. And the page would validate as XHTML as well.

Does anyone have a better solution to this little issue ?