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();
});
});
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:
$(document).ready(function(){
$("img").each(function(index) {
$(this).error(function() {
$(this).hide();
});
$(this).attr("src", $(this).attr("src"));
});
});
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()
and hide()
.
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 to visible
when it loads successfully:
$('div.target img').each(function(){
$(this).imagesLoaded(function(){
$(this).css('visibility','visible');
})
})
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.
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.
setTimeout(function() {
$("img").each(function () {
$(this).error(function () {
$(this).attr("src", "../imageupload/image-failed.png");
});
$(this).attr("src", $(this).attr("src"));
});
}, 100);