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!