[javascript] How can I check if a background image is loaded?

pure JS solution that will add preloader, set the background-image and then set it up for garbage collection along with it's event listener:

Short version:

_x000D_
_x000D_
const imageUrl = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";_x000D_
let bgElement = document.querySelector("body");_x000D_
let preloaderImg = document.createElement("img");_x000D_
preloaderImg.src = imageUrl;_x000D_
_x000D_
preloaderImg.addEventListener('load', (event) => {_x000D_
    bgElement.style.backgroundImage = `url(${imageUrl})`;_x000D_
    preloaderImg = null;_x000D_
});
_x000D_
_x000D_
_x000D_

A bit longer with nice opacity transition:

_x000D_
_x000D_
const imageUrl = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";_x000D_
let bgElement = document.querySelector(".bg-lazy");_x000D_
bgElement.classList.add("bg-loading");_x000D_
let preloaderImg = document.createElement("img");_x000D_
preloaderImg.src = imageUrl;_x000D_
_x000D_
preloaderImg.addEventListener('load', (event) => {_x000D_
  bgElement.classList.remove("bg-loading");_x000D_
  bgElement.style.backgroundImage = `url(${imageUrl})`;_x000D_
  preloaderImg = null;_x000D_
});
_x000D_
.bg-lazy {_x000D_
  height: 100vh;_x000D_
  width: 100vw;_x000D_
  transition: opacity 1s ease-out;_x000D_
}_x000D_
_x000D_
.bg-loading {_x000D_
  opacity: 0;_x000D_
}
_x000D_
<div class="bg-lazy"></div>
_x000D_
_x000D_
_x000D_