首页  >  文章  >  web前端  >  如何检测背景图像何时加载?

如何检测背景图像何时加载?

Barbara Streisand
Barbara Streisand原创
2024-11-14 11:35:02191浏览

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})`;
});

以上是如何检测背景图像何时加载?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn