Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript onerror does not fire on image that throws 404

I have an image from a content provider that needs to be loaded or just replaced by the text.

Example: http://content.etilize.com/Brand-Logo/Black.jpg

This is a brand image that because it doesn't exist for this brand, it gets replaced via headers (from what I understand). So actual error event of image not loading does not happen.

<img src="http://content.etilize.com/Brand-Logo/Black.jpg" onerror="console.log('test')" />

Here is how the request looks like:

Image throws 404, but still loads after. Onerror event not triggered

So when I try to catch the not-loading 404 error, onerror does not trigger at all.

How can I capture this 404 status code?

like image 757
Kalvin Klien Avatar asked Mar 14 '26 11:03

Kalvin Klien


1 Answers

I suggest you to make a request using fetch, and checks the response status. If the status is OK, you just can create an img tag.

Like this example:

fetch('http://content.etilize.com/Brand-Logo/Black.jpg')
  .then((res) => {
    console.log(res)
    // create an <img/> tag using res 
  })
  .catch((e) => console.log("Impossible to load image")) 
like image 192
ianbandrade Avatar answered Mar 16 '26 00:03

ianbandrade



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!