27

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.

Stefano
  • 555
  • 1
  • 5
  • 18

3 Answers3

8

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.

Max
  • 414
  • 1
  • 4
  • 12
7

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.

Seiryoku
  • 83
  • 2
  • 8
  • 15
    I get IDE warnings in JetBrains software for using it as an attribute, fwiw. – dudewad Apr 07 '20 at 03:40
  • 1
    Looked everywhere but can't see why the img element's onerror attribute was marked deprecated in the MDN with [this commit](https://github.com/mdn/browser-compat-data/commit/061483ac41d43acbe9536807dd8be070c9eb031a) in 2017, and unfortunately the change author didn't say. I've been all through the HTML specs, but I don't see what this was based on. Any ideas? – ewbi Nov 21 '20 at 03:18
0

Chrome will ignore the onerror attribute if you put the value directly, like this:

<img src="yourimg.jpg" onerrror="error.png" />

To get around this, use a little JS in the value

<img src="yourimg.jpg" onerrror="this.src='error.png'" />
Elymentree
  • 823
  • 10
  • 22