Home >Web Front-end >JS Tutorial >How Can I Detect When a Background Image Has Loaded?

How Can I Detect When a Background Image Has Loaded?

Barbara Streisand
Barbara StreisandOriginal
2024-11-14 11:35:02234browse

How Can I Detect When a Background Image Has Loaded?

Detecting Background Image Load Status

Aspiring to trigger some code upon the successful loading of a body tag's background image? Introducing a solution to this elusive problem:

The initial approach using $().load() fails due to its limitation to DOM elements, excluding background images. Instead, we employ the following strategy:

  1. Create a new image element and set its src attribute to match the target background image's URL.
  2. Utilize the 'load' event listener to capture the completion of image loading.

In jQuery, this technique translates to:

$('<img/>').attr('src', 'http://picture.de/image.png').on('load', function() {
  $(this).remove(); // Prevent memory leaks suggested by @benweet
  $('body').css('background-image', 'url(http://picture.de/image.png)');
});

Implementing this logic in Vanilla JavaScript:

var src = 'http://picture.de/image.png';
var image = new Image();
image.addEventListener('load', function() {
  body.style.backgroundImage = 'url(' + src + ')';
});
image.src = src;

Elevate your code by encapsulating this functionality into a convenient function that yields a promise:

function load(src) {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.addEventListener('load', resolve);
    image.addEventListener('error', reject);
    image.src = src;
  });
}

const image = 'http://placekitten.com/200/300';
load(image).then(() => {
  body.style.backgroundImage = `url(${image})`;
});

The above is the detailed content of How Can I Detect When a Background Image Has Loaded?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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