BritishSam
BritishSam

Reputation: 1080

Use onError twice

Is there a way to use onError twice if the first onError doesn't exist

<img class="media-object img-responsive" src="/img/product/{{ product_type_slug }}/thumb/{{ image_thumb }}" alt="{{ name }}"
onError="
this.onerror=null;
this.src='/img/product/swatch/{{ image }}';">

Looking for an onError for the onError to show:

src='/img/product/{{ product_type_slug }}/old/{{ image_thumb }}'

so if the original image doesnt exist show swatch url, if that doesnt exist show old.

Upvotes: 2

Views: 2039

Answers (1)

Rogier Spieker
Rogier Spieker

Reputation: 4187

You could use a javascript function to deal with this scenario

function loadAlternative(element, list) {
  var image = new Image();

  image.onload = function() {
    element.src = this.src;
  }

  image.onerror = function() {
    if (list.length) {
      loadAlternative(element, list);
    }
  }

  //  pick off the first url in the list
  image.src = list.shift();
}
<img src="nope.jpg" 
     data-alternative="njet.jpg,neither.jpg,http://lorempixel.com/400/200/technics/1/" 
     onerror="loadAlternative(this, this.getAttribute('data-alternative').split(/,/))">

What this does:

  • you set an error handler to load an alternative image
  • you provide alternatives as a comma-separated list in an data-alternative attribute
  • if the onerror is triggered, the loadAlternative function is called with both the element (img) and the data-alternative list as array
  • for as long as the image cannot be loaded and there is another one in the list, it will repeat the process
  • once an image is loaded, it will be set as src on the element

If you need some default image to be used should all alternatives fail, you could modify the image.onerror function to deal with an empty list like this:

  image.onerror = function() {
    if (list.length) {
      loadAlternative(element, list);
    }
    else {
      element.src = '/every/other/option/has/failed.jpg';
    }
  }

Please note that you could (on the web this means: you will) end up with a lot of attempts to load images, which may be prevented by having the server check for the existence of images.

Upvotes: 2

Related Questions