Home >Web Front-end >JS Tutorial >How to Execute a JavaScript Callback After Successful Image Loading?
Question: How can I execute a JavaScript callback upon the successful loading of an image? Alternatively, is there any means to accomplish this task?
Answer:
There are various methods to achieve image loading callbacks in JavaScript. One approach involves utilizing the .complete property and a callback function, as demonstrated below:
JavaScript Code:
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 approach is standards-compliant, does not require external dependencies, and does not introduce unnecessary delays. The img.complete property is checked initially, and if the image is already loaded, the callback is executed immediately. If the image is not loaded, event listeners are added to the 'load' and 'error' events, ensuring that the callback is executed appropriately.
The above is the detailed content of How to Execute a JavaScript Callback After Successful Image Loading?. For more information, please follow other related articles on the PHP Chinese website!