Home > Article > Web Front-end > How to Ensure a Background Image is Loaded Before Styling the Body?
How to Check if a Background Image is Loaded
In order to ensure that a background image is fully loaded before running any code, such as altering the styling of the body tag, an alternative approach is required. Here's a detailed solution:
const image = new Image();
image.src = 'http://picture.de/image.png';
image.addEventListener('load', function() { // Code to be executed after the image is loaded });
After the image has loaded, you can proceed to apply it as the background image:
const body = document.querySelector('body'); body.style.backgroundImage = `url('${image.src}')`;
For a more structured approach, a promise-based function can be utilized:
function loadImage(src) { return new Promise((resolve, reject) => { const image = new Image(); image.addEventListener('load', () => resolve(image)); image.addEventListener('error', () => reject(`Failed to load image: ${src}`)); image.src = src; }); } loadImage('http://picture.de/image.png').then(image => { body.style.backgroundImage = `url('${image.src}')`; });
The above is the detailed content of How to Ensure a Background Image is Loaded Before Styling the Body?. For more information, please follow other related articles on the PHP Chinese website!