javascriptimagefallbackonerror

Javascript: multiple image onerror handlers


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?


Solution

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