Paulund
2012-01-21 #jquery

Handle Image Loading Errors With jQuery

If an image can't load correctly in the browser it will do a number of things depending on what browser you are using. It will either display a ? question mark image or will just display nothing. When an image can't be found the browser will throw an error, these errors can be found and used by using jQuery. You can add an event handler to your images to see if there is an error, if they return an error you can make jQuery do something. For example if an image can't be found you could change the image to a missing image picture, or just hide the image box which is easy to do in jQuery. Here is a small snippet that will either hide the jQuery box or change the image to something else.

// Hide the image on error
$("img").error(function(){
        $(this).hide();
});

// Change the image to a missing image
$('img').error(function(){
        $(this).attr('src', 'no-image.jpg');
});

IE8 And Lower Bug

The above technique won't work with IE8 or lover because of timing issues so you need to add the following lines in the document.ready function.



$('img').each(function(){
     $(this).attr('src', $(this).attr('src'));
});

This is set the image source to itself on the page load which will then start the error event. But this is will slow the page loading time so you want to make sure you only do this for IE8 or lower.


if ( $.browser.msie && $.browser.version < 9 ) {
$('img').each(function(){
     $(this).attr('src', $(this).attr('src'));
});
}