Javascript: multiple image onerror handlers

54 Views Asked by At

Looking for ways to set multiple fallbacks for image loading in case the original image source threw an exception.

Given an image tag such as <img id="art"> the following JS code sets a fallback image src to album.jpg when the first image cover.jpg throws an error:

var art = document.getElementById('art');

art.src = "cover.jpg";

art.onerror = () => {
    art.src = "album.jpg";
};

How to trigger another onerror handler that will set yet another fallback in case when album.jpg is missing? E.g. if loading cover.jpg fails, and then album.jpg fails too, how to set yet another fallback to e.g. front.jpg and so on?

2

There are 2 best solutions below

0
Andrew Parks On BEST ANSWER

The same onerror handler will fire multiple times, if the src property is updated multiple times.

let art = document.getElementById('art');

let srcs = ['cover.jpg', 'album.jpg','front.jpg', 'empty.png']

art.src = srcs.shift()

art.onerror = e => {
  console.log(`failed to load ${art.src}`)
  if(srcs.length) art.src = srcs.shift()
}
<img id="art">

2
Rory McCrossan On

You don't need to add additional error handlers, the single instance will fire for every change to the src attribute.

Note that this means your current code will create an infinite loop, where it changes the src to 'album.jpg' and that image also fails to load.

To do what you require you can test to see what the current src is and act accordingly. The logic flow can then be amended to prevent the infinite change/error loop by detecting the last possible image.

var art = document.getElementById('art');
art.onerror = e => {
  console.log(`${e.target.src} not found`);
  
  if (e.target.src.endsWith('/cover.jpg'))
    art.src = "album.jpg";
  else if (e.target.src.endsWith('/album.jpg'))
    console.log('Last image - ending loop');  
};

art.src = "cover.jpg";
<img id="art" />

Depending on how many fallback images you have, you may be better off using an array or object to list them, and working through them by index.