Home > Web Front-end > JS Tutorial > How to Reliably Check if a Background Image Has Loaded?

How to Reliably Check if a Background Image Has Loaded?

Mary-Kate Olsen
Release: 2024-11-16 06:54:02
Original
935 people have browsed it

How to Reliably Check if a Background Image Has Loaded?

Using a Background Image Loader

You're attempting to check if a background image has loaded by setting a background image on the body tag and then using the load() function. However, this approach doesn't work effectively for background images.

To truly ensure that the background image has completely loaded, you can utilize a different technique:

$('<img/>').attr('src', 'http://picture.de/image.png').on('load', function() {
   $(this).remove(); // prevent memory leaks
   $('body').css('background-image', 'url(http://picture.de/image.png)');
});
Copy after login

This method creates a new image in memory and attaches a load event listener to it. Once the image has loaded, the load event is triggered, and the background image is set on the body tag.

In vanilla JavaScript, this can be implemented as:

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

You can also create an abstracted function to handle the image loading and return 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})`;
});
Copy after login

This approach allows you to reliably check for the completion of the background image loading and ensures that code is only executed once the image is fully loaded.

The above is the detailed content of How to Reliably Check if a Background Image Has Loaded?. 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