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 on a page with JavaScript.
Listen to the load Event
We can listen to the load
event of a background image to see if it’s loaded.
If it’s loaded, then we can set the background image to the image with the same URL as the background image.
For instance, we can write:
const imageUrl = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
const bgElement = document.querySelector("body");
let preloaderImg = document.createElement("img");
preloaderImg.src = imageUrl;
`
preloaderImg.addEventListener('load', (event) => {
bgElement.style.backgroundImage = `url(${imageUrl})`;
preloaderImg = null;
});
We have the imageUrl
with the image we want to load as the background image.
Then we get the body element with document.querySelector
.
And then we create the preloaderImg
element with document.createElement
with the image we want to preload.
Next, we set the preloaderImg.src
to imageUrl
.
Then we call addEventListener
on preloaderImg
with 'load'
as the first argument to watch for the preloaderImg
loading.
The callback will run when it’s loaded.
And so we can set the bgElement.style.backgroundImage
to set the background image to the image that’s loaded in the preloaderImg
element.
And then we set preloaderImg
to null
to clear the preloaded image.
Now we should see the background image loaded in our page.
Conclusion
We can listen to the load
event of an image element to see if an image is loaded.
Then once it’s loaded, we can use the image URL of the preloaded image to set the background image of the page.