I have tried this code copied from jQuery site, but it fails in IE7/IE8, but works in other browsers. What is wrong with this code, it's from jQuery site(http://api.jquery.com/error/). I'm using jQuery version 1.4.4.
$(document).ready(function(){
$("img").error(function(){
$(this).hide();
});
});
In my case in IE8, my replacement image was still not loading. The code below fixed this for me. You might have to play around with the timeout delay, to find out what works best.
The problem is that by the time
$(document.ready)
is executed, the image has already finished loading so the load/error events won't be triggered anymore.The only way I can think of to bypass this is to reload the image, thus "force" the event to be triggered:
It shouldn't be too bad on performance as the images will be taken most probably from the cache, not really reloaded from the server.
Live test case (with cool cats ;)) is available here: http://jsfiddle.net/yahavbr/QvnBC/1/
Using the above solution will still cause a brief appearance of the 'broken image icon', because there is a latency between
error()
andhide()
.I used the jQuery imagesloaded plugin which allows callback when image successfully loaded. First I set the image to
visibility:hidden
. Then I set it tovisible
when it loads successfully:This uses a bit more resource, but will prevent the 'broken image icon' from showing at all. I do not use this site-wide, but only sections where broken image is possible.