Categories
JavaScript Answers

How to check if a background image is loaded with JavaScript?

Spread the love

Sometimes, we want to check if a background image is loaded with JavaScript.

In this article, we’ll look at how to check if a background image is loaded with JavaScript.

How to check if a background image is loaded with JavaScript?

To check if a background image is loaded with JavaScript, we can set the backgroundImage property.

For instance, we write

const src = "https://picsum.photos/200/300";
const image = new Image();
image.addEventListener("load", () => {
  body.style.backgroundImage = `url(${src})`;
});
image.src = src;

to create the img element with Image.

Then we listen for the load event on the image to check if it’s loaded.

If it is, then we set the backgroundImage to the URL of the loaded image.

Then we load the image by setting image.src to src.

Conclusion

To check if a background image is loaded with JavaScript, we can set the backgroundImage property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *