Home > Web Front-end > JS Tutorial > How to Ensure a Background Image Loads Before Code Execution?

How to Ensure a Background Image Loads Before Code Execution?

Mary-Kate Olsen
Release: 2024-11-17 08:07:03
Original
680 people have browsed it

How to Ensure a Background Image Loads Before Code Execution?

Ensuring Background Image Loading Before Code Execution

Incorporating a background image into the body tag and initiating subsequent code execution can pose a challenge when determining if the image has fully loaded. Using the conventional load() function, as seen in the provided example, won't suffice.

Solution:

To overcome this hurdle, consider the following approach:

$('<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 code creates a new image in memory, utilizing the load event to detect when the source image has been loaded. By removing the image after loading, potential memory leaks are avoided.

Vanilla JavaScript Implementation:

For vanilla JavaScript, the solution takes the following form:

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

Promise-Based Abstraction:

To abstract the process, a handy function can be created, returning 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

The above is the detailed content of How to Ensure a Background Image Loads Before Code Execution?. 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