Home >Web Front-end >JS Tutorial >How Can I Reliably Check if an Image Has Loaded in jQuery, Including Error Handling?

How Can I Reliably Check if an Image Has Loaded in jQuery, Including Error Handling?

Barbara Streisand
Barbara StreisandOriginal
2024-12-08 15:11:12286browse

How Can I Reliably Check if an Image Has Loaded in jQuery, Including Error Handling?

jQuery: Checking if an Image is Loaded (Handling Errors)

In jQuery, you can check if an image is loaded using the load() and error() events. However, there is a limitation when an error occurs before jQuery registers these events.

To address this, you can verify the image's complete property to ensure it wasn't already loaded before jQuery could act. However, this approach fails to detect errors that occur before the events are registered.

Solution:

A more robust solution involves checking both the complete and naturalWidth properties in the following order:

function IsImageOk(img) {
  // Check if the image is complete
  if (!img.complete) {
    return false;
  }

  // Check if the image has a valid natural width
  if (img.naturalWidth === 0) {
    return false;
  }

  // Assume the image is okay
  return true;
}

By checking complete first, you can quickly determine if the image has already loaded. If it hasn't, you then examine naturalWidth, which provides the true size of the image. If it's zero, the image failed to load. This approach ensures that both loading successes and errors before jQuery event registration are detected.

The above is the detailed content of How Can I Reliably Check if an Image Has Loaded in jQuery, Including Error Handling?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn