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:
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中文网其他相关文章!