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 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>

Comments

Popular posts from this blog

The "Read aloud selection" feature in Edge browser

HOW TO copy a doc / spreadsheet from Google Docs to OneDrive without saving to local computer

Get Google Search results by SMS, talking to iPhone