Alternative Ways to Handle Image Loading with a Callback
When loading an image, knowing when it has completed can be crucial for implementing specific functionalities. This question explores options for executing a callback upon image load in JavaScript.
Solution 1: .complete Callback
A reliable and standards-compliant approach involves using the .complete property along with a callback function. .complete checks if the image has already finished loading, ensuring that the callback is triggered immediately if applicable.
var img = document.querySelector('img'); function loaded() { alert('loaded'); } if (img.complete) { loaded(); } else { img.addEventListener('load', loaded); img.addEventListener('error', function() { alert('error'); }); }
This code:
Additional Notes
This approach is highly efficient as it triggers the callback as soon as the image is ready, avoiding unnecessary delays caused by event listener waiting. It is also supported by major browsers and allows for easy error handling.
The above is the detailed content of How Can I Execute a Callback Function After an Image Loads in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!