Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (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).

like image 960
Prem Avatar asked Jan 04 '12 21:01

Prem


People also ask

How can you tell if an image is not loaded?

Using attributes of <img> to check whether an image is loaded or not. The attributes we will use are: onload: The onload event is triggered when an image is loaded and is executed. onerror: The onerror event is triggered if an error occurs during the execution.

How do you check if an image has loaded Javascript?

To determine whether an image has been completely loaded, you can use the HTMLImageElement interface's complete attribute. It returns true if the image has completely loaded and false otherwise. We can use this with naturalWidth or naturalHeight properties, which would return 0 when the image failed to load.


1 Answers

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+

like image 174
benesch Avatar answered Sep 19 '22 06:09

benesch