Home >Web Front-end >JS Tutorial >How to Determine if a Background Image Has Fully Loaded in JavaScript?

How to Determine if a Background Image Has Fully Loaded in JavaScript?

DDD
DDDOriginal
2024-11-15 18:17:02898browse

How to Determine if a Background Image Has Fully Loaded in JavaScript?

Determining the Loading Status of a Background Image

In web development, setting a background image on various elements, such as the body tag, is a common practice. However, ensuring that the image has fully loaded before executing subsequent code can be a challenge.

To address this issue, 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)');
});

This method creates an invisible image element in memory and assigns the desired background image URL to its source attribute. By listening for the load event, you can detect when the image has been fully loaded and then apply it as the background image for the specified element.

In JavaScript, the code would appear as:

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

Alternatively, you can abstract this functionality into a promise-returning function:

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(() => {
    document.body.style.backgroundImage = `url(${image})`;
});

This approach enables you to handle the image loading process asynchronously and conditionally perform subsequent actions only when the image is available.

The above is the detailed content of How to Determine if a Background Image Has Fully Loaded in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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