Check if an image is loaded (no errors) with jQuery

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 it does something else. I'm using jQuery load() and error() methods as events. After these events I check the image DOM element for the .complete to make sure the image wasn't already loaded before jQuery could register the events.

It works correctly except when an error occurs before jQuery can register the events. The only solution I can think of is to use the img onerror attribute to store a "flag" somewhere globally (or on the node it's self) that says it failed so jQuery can check that "store/node" when checking .complete.

Anyone have a better solution?

Edit: Bolded main points and added extra detail below: I'm checking if an image is complete (aka loaded) AFTER I add a load and error event on the image. That way, if the image was loaded before the events were registered, I will still know. If the image isn't loaded after the events then the events will take care of it when it does. The problem with this is, I can easily check if an image is loaded already, but I can't tell if an error occurred instead.


Solution 1:

Check the complete and naturalWidth properties, in that order.

https://stereochro.me/ideas/detecting-broken-images-js

function IsImageOk(img) {
    // During the onload event, IE correctly identifies any images that
    // weren’t downloaded as not complete. Others should too. Gecko-based
    // browsers act like NS4 in that they report this incorrectly.
    if (!img.complete) {
        return false;
    }

    // However, they do have two very useful properties: naturalWidth and
    // naturalHeight. These give the true size of the image. If it failed
    // to load, either of these should be zero.
    if (img.naturalWidth === 0) {
        return false;
    }

    // No other way of checking: assume it’s ok.
    return true;
}

Solution 2:

Another option is to trigger the onload and/or onerror events by creating an in memory image element and setting its src attribute to the original src attribute of the original image. Here's an example of what I mean:

$("<img/>")
    .on('load', function() { console.log("image loaded correctly"); })
    .on('error', function() { console.log("error loading image"); })
    .attr("src", $(originalImage).attr("src"))
;

Hope this helps!

Solution 3:

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 naturalWidth and naturalHeight must 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.