I want to set a background image on the body tag, then run some code - like this:
$(\'body\').css(\'background-image\',\'http://picture.de/image.png\').load(
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:
const imageUrl = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
let bgElement = document.querySelector("body");
let preloaderImg = document.createElement("img");
preloaderImg.src = imageUrl;
preloaderImg.addEventListener('load', (event) => {
bgElement.style.backgroundImage = `url(${imageUrl})`;
preloaderImg = null;
});
A bit longer with nice opacity transition:
const imageUrl = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
let bgElement = document.querySelector(".bg-lazy");
bgElement.classList.add("bg-loading");
let preloaderImg = document.createElement("img");
preloaderImg.src = imageUrl;
preloaderImg.addEventListener('load', (event) => {
bgElement.classList.remove("bg-loading");
bgElement.style.backgroundImage = `url(${imageUrl})`;
preloaderImg = null;
});
.bg-lazy {
height: 100vh;
width: 100vw;
transition: opacity 1s ease-out;
}
.bg-loading {
opacity: 0;
}