Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should I use instead of the deprecated `onerror` attribute?

On my images I'm setting the onerror attribute so that a placeholder is used in case the image is not available for some reason:

<img
    class="article-img"
    src="path-to-image.jpg"
    alt="some description"
    onerror="this.src='/images/fallback.png'"
>

Now, it looks like onerror has been deprecated, but I couldn't find any good source on what would be the suggested alternative way of handling the error (possibly in a similarly compact fashion).

It would be also interesting to know why it was deprecated.

like image 252
Stefano Avatar asked Sep 17 '19 18:09

Stefano


People also ask

Is Onerror deprecated?

However, the HTML onerror attribute is indeed deprecated (see on MDN), but it should not be triggered in JSX code.

What is Onerror in IMG tag?

Definition and Usage The onerror event is triggered if an error occurs while loading an external file (e.g. a document or an image). Tip: When used on audio/video media, related events that occurs when there is some kind of disturbance to the media loading process, are: onabort.


2 Answers

According to MDN, it seems to be deprecated as an img tag attribute but not as a global event; GlobalEventHandlers.onerror is still valid, and seemingly, they haven't classified the tag attribute event as deprecated there (in that section) yet, they're still showing an img attribute example.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror

So you can still use it, but just don't use it as a tag attribute, you can place it inside a script tag or a separate file.

By the way I've just tested an img tag with an onerror attribute on the w3c validator and it's not marking it as error neither as a warning.

like image 93
Seiryoku Avatar answered Sep 19 '22 07:09

Seiryoku


I think that was a mistake.

WHATWG still mention onerror in their HTML living standard specification.

Also, onerror attribute on img elements is not included in their obsolete features list.

like image 30
Max Avatar answered Sep 18 '22 07:09

Max