Find and hide broken images in js

Ever run into the issue where dynamic content loads on a page and occasionally contains a broken image icon (and a 404 on the get request for the image)? Well, I have…

So here’s my plan:

function isImageOk(img) {

	if (!img.complete) {
		return false;
	}

	if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
		return false;
	}

	return true;
}

Then you can bind this to the window and search for all img tags:

addEvent(window, "load", function() {
	for (var i = 0; i < document.images.length; i++) {
		if (!isImageOk(document.images[i])) {
		document.images[i].style.visibility = "hidden";
		}
	}
});

Or if you’re using jquery:

$(document).ready(function(){
	$(".img").each(function(index, elem){
	if (!isImageOk(elem)) {
		$(elem).css("visibility", "hidden");
	}
	});
});

Obviously you could do more than set the visibility to hidden: Add a class to the deviant images, remove from DOM, display: none, add a pink border, destroy the DOM at first instance of a broken image, etc…