Image fallback

by Patrik Affentranger

HTML

<img src="invalid_link" onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';">

<img src="https://placeimg.com/200/300/animals" alt="My cool image" srcset="path/to/actual/image" />


<img src="invalid_link" alt="Original alt" onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';this.alt='new alt'">

<img
  src="invalid_link"
  alt="Original alt"
  data-fallback-url='https://placeimg.com/200/300/animals'
  onerror="fallbackImage(this)">


<img
  src="invalid_link"
  alt="Original alt"
  data-fallback-url='https://placeimg.com/200/300/animals'
  data-fallback-alt="New alt"
  onerror="fallbackImage(this)">

JavaScript

function fallbackImage(el) {
	if (el.hasAttribute('data-fallback-url')) {
    el.onerror = null;                                  // resetting the error so avoid an endless loop
    el.src = el.getAttribute('data-fallback-url');      // update the src
    el.alt = el.getAttribute('data-fallback-alt') || '' // update the `alt` attribute for a11y
  }
}