Home  >  Article  >  Web Front-end  >  How to Ensure a Background Image is Loaded Before Styling the Body?

How to Ensure a Background Image is Loaded Before Styling the Body?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-17 20:55:02633browse

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:

  1. Creating an Image Object:
const image = new Image();
  1. Setting Image Source:
image.src = 'http://picture.de/image.png';
  1. Using the Load Event:
image.addEventListener('load', function() {
  // Code to be executed after the image is loaded
});
  1. Applying Background Image:

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}')`;
  1. Using a Promise-Based Solution:

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!

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