Most techniques to style broken images rely on browser hacks and are very inconsistent. Let me show you a consistent way that works the same way across every browser.
This technique relies on the HTMLMediaElement.onerror
property, which is supported in almost every browser, all the way back to IE9. Take a look:
On all our images, we will add an onerror
event handler which will change the src of our image to a predefined one
<img src="/path/toimage" alt="my image"
onerror="this.onerror=null;this.src='/broken-img.svg';this.classList.add('broken-img');">
What’s happening here?
We are hooking into the onerror
event which fires when some form of error occurs while attempting to load or perform the media. When the event fires, we replace the src
of the image to point to A NEW image and adds the class broken-img
to our image.
On Swish, I use this image, an SVG that is only 855B in size, and will be loaded once no matter how many times it appears on the page.
This part this.onerror=null
prevents the browser from falling into an infinite loop if the onerror
handler has a problem, maybe if the new image was also unable to be loaded. Although some browsers evaluate the onerror
handler just once, others will attempt to run it again and again if an error keeps occurring.
With the broken-img
class, we can add any further styling that only applies when the image is broken. On Swish, I limit the height of the image to 5em
.broken-img {
max-height: 5em;
}
Conclusion
I think this is the best way to handle broken images, we use a system that is guaranteed to work the same way across browsers and has practically no adverse effects on our website’s peformance.
Top comments (0)