1

I am running a very simple slide show that changes the background of a div after some time. The problem is that the images are loaded too slow and a blank screen appears between image changes. Now I want to preload the images and I found these answers, but they did not work, and:

var myImage = new Image();
myImage.src = 'picture.jpg';

Can I somehow use this myImage as background-image of a div? Or do you know any other methods for preloading background-images?

Using :after pseudo-elements did not work.

Anno
  • 761
  • 1
  • 10
  • 22
  • maybe try this one: https://stackoverflow.com/a/61762176/8620333 – Temani Afif Jul 08 '20 at 16:18
  • Please provide the exact code you tried, or at least a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – kmoser Jul 08 '20 at 16:37

1 Answers1

0

You can do that using blobs and URL.createObjectURL().

let imgUrl = "https://i.imgur.com/VG2UvcY.jpg";

const preloadBtn = document.getElementById("preload-btn"),
      showBtn = document.getElementById("show-btn");


preloadBtn.addEventListener("click", async () => {
  imgUrl = URL.createObjectURL(
    await (await fetch(imgUrl)).blob()
  );
  preloadBtn.disabled = true;
});

showBtn.addEventListener("click", () => {
  document.body.style.backgroundImage = `url("${imgUrl}")`
});
body {
  background-size: cover;
}
<button id="preload-btn">Preload big image</button>
<button id="show-btn">Show big image</button>
D. Pardal
  • 6,173
  • 1
  • 17
  • 37