-2

I have a <img> placeholder where I want to show images using a slideshow effect:

<img rel="preload" class="home-postcard" src="/img/Rsquare1.jpg" />

I am running this JS script:

var iloop = 0;
window.setInterval(function () {
    var dataArray = new Array("/img/Rsquare2.jpg", "/img/Rsquare3.jpg");
    $("img.home-postcard").fadeOut("fast", function () {
        $(this).attr("rel", "preload");
        $(this).attr("src", dataArray[iloop]);
        iloop++;
        if (iloop === dataArray.length) {
            iloop = 0;
        }
        $(this).fadeIn("slow");
    });
}, 10000);

The animation works, but images keep downloading from the network over each iteration and it consumes bandwidth.

I tried to preload the images using rel="preload", but they keep downloading each time the src is rewritten.

What am I missing?

Note: I previously tried this preloading method but images keep downloading whenever the src attribute is rewritten. Preloading images with jQuery

Note 2: rel="preload" is referenced as a potential method: https://developers.google.com/web/updates/2016/03/link-rel-preload

E_net4
  • 27,810
  • 13
  • 101
  • 139
Alfred Wallace
  • 1,741
  • 1
  • 14
  • 32

1 Answers1

1

External content - such as images - is downloaded to the browser's cache and for subsequent requests loaded from there instead of being re-downloaded. The only exception to this is if the browser's cache has been deactivated manually - or maybe if it's full.

The following simple example illustrates this. I'm using the setInterval function to update an img element with two images out of an array every two seconds. If you open the developer tools of your browser and take a look at the 'networking section', you'll notice that even though the slideshow might have run for a minute yet there are just two http requests for the pictures.

var images = ["https://picsum.photos/id/815/200/300", "https://picsum.photos/id/835/200/300"];
var counter = 0;

function update() {
  var img = document.getElementById("myImg").src = images[counter];
  if (counter + 1 < images.length) {
    counter++;
  } else {
    counter = 0;
  }
}
var interval = setInterval(update, 2000);
<img id="myImg">
obscure
  • 11,916
  • 2
  • 17
  • 36