Home > Web Front-end > JS Tutorial > How Can I Execute a Callback Function After an Image Loads in JavaScript?

How Can I Execute a Callback Function After an Image Loads in JavaScript?

DDD
Release: 2024-11-28 09:39:10
Original
204 people have browsed it

How Can I Execute a Callback Function After an Image Loads in JavaScript?

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

This code:

  1. Initializes an image element with img.
  2. Defines a callback function loaded to handle the image load.
  3. Checks if the image is already complete using .complete.
  4. If complete, invokes the callback immediately.
  5. If not complete, attaches event listeners for both 'load' (to execute the callback on load) and 'error' (to notify of failed loading).

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template