Tip: How to handle broken images in HTML

I found this small but very good article in phpied.com by Stoyan StefanovTwitter page. The article tells about handling broken images in a web page, especially when we dont have control over what we load in our page.

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.

The solution is very simple.

<img src="broken.png"
  onerror="this.style.display='none'"
/>

Read the article here

Advertisements