简体   繁体   中英

Javascript - onerror event doesn't work in firefox

<img style="" src="" onerror='this.style.visibility = "hidden"' />

This very simple onerror event handler hides the image if it can't be found.

It works as intended in Chrome, but in Firefox, it does nothing.

Here is a jsFiddle you can try running in Chrome and Firefox to see it in action.

http://jsfiddle.net/y9e88ack/

Why does firefox not work?

Any help would be appreciated

I'm not sure of the internal reasoning between browsers, but Firefox will gladly fire the onerror callback when an invalid, non-empty attribute is provided. For example:

<img style="" src="asdf.jpg" onerror='this.style.visibility = "hidden"' />

DEMO: http://jsfiddle.net/18ga9hh8/

In both browsers, when there's an empty src attribute, there is no request made to the server (watched with Developer Tools' network tab).

When an invalid, non-empty src is provided, a request is made and both receive a 404 response, triggering the onerror callback (expected).

As you've pointed out, using a value of "?" forces your desired behavior on both browsers. What it does is make a request (can be the current page's URL, or the current page's directory, because it is considered a relative path - depends on what the browser is designed to do) but fails to apply it as an image (it's an HTML response), causing the error.

If you're wondering or care, the HTML5 spec says this about the src attribute:

The src attribute must be present, and must contain a valid non-empty URL potentially surrounded by spaces referencing a non-interactive, optionally animated, image resource that is neither paged nor scripted.

And if you look a little further down the page to the list for When the user agent is to update the image data of an img element, it must run the following steps , #10 says the following:

If selected source is null, then set the element to the broken state, queue a task to fire a simple event named error at the img element, and abort these steps.

So it looks like Firefox isn't adhering to the spec, but maybe I'm interpreting it wrong?

Using the W3C validator, an empty src attribute causes a validation error, while using a value of "?" is valid (remember the whole relative path thing?). Note that adding a querystring (what the ? should be doing) is supposed to cause the browser to never cache the image, so I don't think caching of actual images can be achieved using this approach, if desired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM