title: how to preload images for javascript slideshow
body: <p>I wrote a simple JavaScript slideshow where the background is changed after some time via CSS background property. The problem is that on devices with low bandwidth the slideshow shows blank images when the images are not loaded. My solution would be to preload all images and start the slideshow when all images are loaded. How can I preload the images and use them as background?</p>
  
  <p>index.html:</p>
  
  <pre><code>&lt;html&gt;
    &lt;head&gt;
    &lt;/head&gt;
    &lt;body&gt;
      &lt;div class="jumbotron" style="width:200pt; height:200pt"&gt;&lt;/div&gt;
  
      &lt;script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"&gt;&lt;/script&gt;
      &lt;script src="slideshow.js"&gt;&lt;/script&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>slideshow.js:</p>
  
  <pre><code>$(window).on("load", function () {
    // List of image paths.
    var background_images = ["image1.jpg", "image2.jpg"]
  
    // Every X miliseconds change the background image.
    var X = 4000
    backgroundImageIdx = 0;
    window.setInterval(function () {
      $(".jumbotron").css("background-image", "url(" + background_images[backgroundImageIdx] + ")");
      backgroundImageIdx++;
      if (backgroundImageIdx &gt;= nrOfBackgroundImages) {
        backgroundImageIdx = 0;
      }
    }, X);
  }
  </code></pre>