So there seems to be quiet a few ways to handle broken images on a html page. I would like to know what ways are in popular use and what ways are viewed to be best practice?

To start I've looked at some myself like:

function imgErr(source) {     
    source.src = /images/missing.jpg";
    source.onerror = "";
    return true;
}
<img src="test.jpg" alt="test" title="test" onerror="imgErr(this);" />

Pros: works everytime, the event will always be caught. User never sees broken image. Seems to work well across the browsers. Cons: onerror tag required on each image, function imgErr(source) needs to be in the head to catch the errors, slows down the users experienced load time

$('img').error(function(){
  $(this).attr('src', 'missing.jpg');
});

Pros: very little code, works on all images without changing their markup, can be place outside of the head Cons: can miss the error event depending on the speed of the pages onload event, slows down the users experienced load time

$(window).load(function() {
    $("img").each(function() {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
            var src = $(this).attr("src");
            var suffix = src.substring(src.length - 6, src.length).split('.')[0];
            suffix = suffix.charAt(suffix.length - 1);            
            $(this).attr("src", "/static/images/generic/missing_" + suffix + ".jpg");
        }
    });
});

Pros: Can be placed anywhere on the page, will fix the images no matter when it gets to run, doesn't slow down the users experienced load time Cons: shows a broken image till it runs creating a poor user experience

In my situation load time is the greatest issue but I can't get the last option to work in IE properly as it changes broken and none broken images alike!

Cheers, Denis

Edit
Report