Home >Web Front-end >JS Tutorial >How Can I Reliably Check for Successful Image Loading and Errors with JavaScript?

How Can I Reliably Check for Successful Image Loading and Errors with JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-21 16:03:10483browse

How Can I Reliably Check for Successful Image Loading and Errors with JavaScript?

How to Verify Image Loading Success and Errors with jQuery

Manipulating image thumbnails with jQuery involves handling both successful loading and errors. While jQuery's load() and error() methods help, they may not detect issues that arise before their registration.

One approach is to check the image DOM element's .complete property, ensuring the image isn't already loaded before triggering jQuery events. However, this method fails to detect errors that precede event registration.

A more effective solution is to check both the .complete and .naturalWidth properties, as suggested by stereochro.me:

function IsImageOk(img) {
    // Check for incomplete images
    if (!img.complete) {
        return false;
    }

    // Check for zero width in failed images
    if (img.naturalWidth === 0) {
        return false;
    }

    // Assume image is valid
    return true;
}

This function systematically verifies image loading success and detects errors that arise even before jQuery event registration.

The above is the detailed content of How Can I Reliably Check for Successful Image Loading and Errors with JavaScript?. 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