Hide broken images
I know, you don't have broken images on your site, it's unprofessional and ugly. But sometimes you may be loading images that you don't control and you never know what's going on on the other server you're expecting to serve, but it may not feel up to the task.
One nice and simple strategy to deal with this uncertainty is to hide the images that fail to load. Browsers sent an "error" event when the worst happens and an image fails for whatever reason. Subscribe to this event using your favorite event-listener-attaching approach or library and hide the image.
Or with some ugly old-school inline event handler:
<img src="broken.png" onerror="this.style.display='none'" />
Simple, eh?
This entry was posted on Monday, February 16th, 2009 and is filed under images. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Get notification for future posts: follow me on Twitter or subscribe to my RSS feed

February 16th, 2009 at 4:58 am
[...] a comment » I found this small but very good article in phpied.com by Stoyan Stefanov – Twitter page. The article tells about handling broken images in a web page, [...]
February 16th, 2009 at 5:12 am
That’s right, this is a great way to hide broken images. That’s why I did the wp-broken-images WordPress plugin back in 2007:
http://wordpress.org/extend/plugins/wp-broken-images/
My plugin uses a little bit more “extended” approach, since not everyone would like to hide the broken images, but probably swap them with another image, or do some CSS styling.
Anyway, the only downside is that this approach requires JavaScript, and if it’s not on because of some browser blocking addon, then it can’t do its thing. Fortunately those cases are happening too rarely
February 16th, 2009 at 5:17 am
One more thing: I tried to use the “event-listener-attaching approach” but I could not get it work, because I don’t know when to start my code that attached the event listener. Using document.ready or window.load is too late, because the onerror event of the images was already triggered (prior to document.ready and window.load events). And on the other hand until the whole HTML is loaded I don’t know how many images are there. What event or approach would you suggest to do this “event-listener-attaching approach” ?
February 16th, 2009 at 5:51 am
Hmm, good point. Well, if DOMContentReady is too late, then inline onerror might be the only working solution. Short of following each <img> with inline <script> which is impractical and no better then inline onerror.
February 16th, 2009 at 6:05 am
This is really good. Thank you.
February 23rd, 2009 at 2:48 pm
[...] http://www.phpied.com/hide-broken-images/ : une technique pour ne pas afficher les images cassées [...]
June 1st, 2010 at 1:25 am
Hi,
Thanks for the share.. helped me…
March 5th, 2011 at 5:06 am
woh its work.
thanks for sharing