Home > Article > Web Front-end > How Can I Detect When a Background Image Has Loaded?
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})`; });
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!