Home > Web Front-end > JS Tutorial > How to Execute a JavaScript Callback After Successful Image Loading?

How to Execute a JavaScript Callback After Successful Image Loading?

Linda Hamilton
Release: 2024-11-27 21:24:14
Original
743 people have browsed it

How to Execute a JavaScript Callback After Successful Image Loading?

Image Loading and JavaScript Callbacks

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')
  })
}
Copy after login

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!

Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template