Skip to content Skip to sidebar Skip to footer

How To Handle Image Not Found Error In Html5 Picture Tag

I am trying to use the below piece of code:

Solution 1:

Yes, use the onerror event. Then, you can simply change the src attribute:

let image = document.querySelector('img');
image.onerror = function() {
  if (this.src === 'default1.png') this.src = 'default2.png';
  elseif (this.src !== 'default2.png') this.src = 'default1.png';
}

This will change the src of the image from whatever it was to 'default1.png' and then, if it fires again, to 'default2.png'.

Solution 2:

<picture>
  <source srcSet="image.webp"type="image/webp" />
  <source srcSet="image.jpeg"type="image/jpeg" />
  <source srcSet="image.png"type="image/png" />
  <img srcSet="image.jpg" onError={(e) => {
    e.target.onerror = null;
    e.currentTarget.parentNode.children[0].srcset = e.target.src;
    e.currentTarget.parentNode.children[1].srcset = e.target.src;
    e.currentTarget.parentNode.children[2].srcset = e.target.src;
    e.currentTarget.parentNode.children[3].srcset = e.target.src;
  }} />
</picture>

Post a Comment for "How To Handle Image Not Found Error In Html5 Picture Tag"