I\'m using JavaScript with the jQuery library to manipulate image thumbnails contained in a unordered list. When the image is loaded it does one thing, when an error occurs
Based on my understanding of the W3C HTML Specification for the img element, you should be able to do this using a combination of the complete and naturalHeight attributes, like so:
function imgLoaded(imgElement) {
return imgElement.complete && imgElement.naturalHeight !== 0;
}
From the spec for the complete attribute:
The IDL attribute complete must return true if any of the following conditions is true:
- The src attribute is omitted.
- The final task that is queued by the networking task source once the resource has been fetched has been queued.
- The img element is completely available.
- The img element is broken.
Otherwise, the attribute must return false.
So essentially, complete returns true if the image has either finished loading, or failed to load. Since we want only the case where the image successfully loaded we need to check the nauturalHeight attribute as well:
The IDL attributes
naturalWidthandnaturalHeightmust return the intrinsic width and height of the image, in CSS pixels, if the image is available, or else 0.
And available is defined like so:
An img is always in one of the following states:
- Unavailable - The user agent hasn't obtained any image data.
- Partially available - The user agent has obtained some of the image data.
- Completely available - The user agent has obtained all of the image data and at least the image dimensions are available.
- Broken - The user agent has obtained all of the image data that it can, but it cannot even decode the image enough to get the image dimensions (e.g. the image is corrupted, or the format is not supported, or no data could be obtained).
When an img element is either in the partially available state or in the completely available state, it is said to be available.
So if the image is "broken" (failed to load), then it will be in the broken state, not the available state, so naturalHeight will be 0.
Therefore, checking imgElement.complete && imgElement.naturalHeight !== 0 should tell us whether the image has successfully loaded.
You can read more about this in the W3C HTML Specification for the img element, or on MDN.