To do this, you need to hook the error
event, then go back and check the images to see if any of them have already errored (before you hooked the event) to handle them. Along these lines:
var defaultImage = "ImgAlt.jpg";
$("img").one("error", function() {
this.src = defaultImage;
}).each(function() {
if (this.complete && !this.naturalWidth) {
this.src = defaultImage;
$(this).off("error");
}
});
complete
will be true
when the image is broken. naturalWidth
will be the natural width of the image, and either 0
or undefined
if it's broken. Sadly that latter check is just about the only way to know the image is broken, since they lack any (blindingly-obviously-needed) error indicator after the event. (naturalWidth
is supported by all modern browsers and also IE9-IE11; it is not supported by the truly-obsolete IE8.)
Note the assumption that none of the images you want to load is actually zero-width. Seemed like a safe assumption. :-)