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

How Can I Run a JavaScript Callback After an Image Loads?

Linda Hamilton
Release: 2024-12-04 14:31:12
Original
791 people have browsed it

How Can I Run a JavaScript Callback After an Image Loads?

Running a JavaScript Callback on Image Load

Question

Is there a way to execute a callback function when an image has finished loading?

Answer

Using .complete Callback

This method is standards-compliant and has low dependency requirements. Additionally, it avoids unnecessary delays:

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

Source

The above code snippet is based on the following resource:

  • [HTML5 Rocks: Promises](http://www.html5rocks.com/en/tutorials/es6/promises/)

The above is the detailed content of How Can I Run a JavaScript Callback After an Image Loads?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template