简体   繁体   中英

JavaScript: Is there an error property for failed image requests?

An HTML <img> element has a boolean complete property, which is true if the image has successfully loaded (or if it hasn't yet been assigned a src ). It also has an onload event, which fires when the image successfully loads, and an onerror event, which fires when the image fails to load (eg due to a broken link, corrupt image, or offline network).

Now... what I want to know is if there is a property on an image element that denotes that the image has already failed to load . Assume that I cannot use the onerror event, because the script may only have access to the image after the event has fired. What we are looking for is a simple boolean lookup property like complete that says "the loading of this image was already attempted, and it failed". (Which I don't see in the spec, but I'm wondering if I'm missing something).

You can use naturalWidth and naturalHeight for a similar effect in almost all browsers (IE8 and below do not support this property). The naturalXX properties contain the original height/width of the image, before modifications through HTML/CSS attributes/styling. So if naturalWidth == 0 , you know the image has failed to load.

(Note that you can't use the standard width or height properties, since those will return the size of the notfound placeholder image.)

document.getElementById("image").naturalWidth ? "success" : "fail"

If you're just trying to change the not found placeholder image, there's a nifty HTML solution for that :

<object data="https://stackoverflow.com/does-not-exist.png">
  <img src="https://stackoverflow.com/content/img/so/logo.png">
</object>

fiddle: http://jsfiddle.net/K3dwX/1/

PS: Potential solution for IE6+

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