Skip to content Skip to sidebar Skip to footer

Caching Dynamically Loaded Images

I'm using javascript to dynamically load any of a series of images into a single img tag, based on user interaction: function reassignImage(newSource) { img.src = newSource; }

Solution 1:

What's the cache-control header set to in the http response for the image? (Chrome developer tools will show you). If it's not set to be cacheable, it will get refetched.


Solution 2:

This will pre-load an image so that the browser can display it immediately when you actually set the src of an img tag. I speculate that pre-loading an image like this will ensure it's in the cache so it won't reload, though I haven't tested it.

var myImg = new Image(25, 25);
myImg.src = "/foobar.png";

In other words, this should now hopefully only download two images

function reassignImage(newSource) {
    var myImg = new Image(25, 25);
    myImg.src = newSource;
    img.src = newSource;
}

reassignImage("first.png");
reassignImage("second.png");
reassignImage("first.png");

Edit

I was doing it wrong. Try creating a new Image() for every new file the user loads. Swap these image elements in and out of the dom.

<html>
  <head>
    <script>
    var imageElements = {};
    function reassignImage(newSource) {
      if (typeof imageElements[newSource] == "undefined") {
        imageElements[newSource] = new Image();
        imageElements[newSource].src = newSource;
      }
      var container = document.getElementById("imageContainer");
      container.innerHTML = '';
      container.appendChild(imageElements[newSource]);
    }
    </script>
  </head>
  <body>
    <div id="imageContainer"></div>
  </body>
</html>

Post a Comment for "Caching Dynamically Loaded Images"