HOW TO Add a Backup Image in HTML When the Main Image Fails to Load
In HTML, an image can use a backup source with the onerror event. The browser first tries to load the main image from src. If that image is missing, blocked, or fails to load, onerror runs and replaces it with a fallback image.
<img
src="actual-image.jpg"
alt="Product image"
onerror="this.onerror=null; this.src='backup-image.jpg';"
>
The JavaScript code
this.onerror=null
prevents an infinite loop if the backup image also fails.
That prevents an endless loop if the backup image also fails. Without it, the browser could keep triggering onerror again and again.
This technique is useful for product images, profile photos, brand logos, or any place where a missing image should show a placeholder instead of a broken image icon.
For instance, this Dynamic Dummy Image Generator can be used to generate placeholder images of desired dimensions.
For multiple responsive image options, use <picture>, but that is for format/viewport fallback, not broken-image fallback:
<picture>
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="Product image">
</picture>
Lorempics and JSONExamples also provide similar dynamic image generation service with the additional ability to change font size.

Comments
Post a Comment