Home > Web Front-end > JS Tutorial > 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
Release: 2024-11-17 20:55:02
Original
701 people have browsed it

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();
Copy after login
  1. Setting Image Source:
image.src = 'http://picture.de/image.png';
Copy after login
  1. Using the Load Event:
image.addEventListener('load', function() {
  // Code to be executed after the image is loaded
});
Copy after login
  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}')`;
Copy after login
  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}')`;
});
Copy after login

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!

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