Reputation: 16239
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 (e.g. 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).
Upvotes: 6
Views: 1357
Reputation: 5269
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+
Upvotes: 2