0

I am running a website where images get updated automatically and very frequently. The image src's stay the same but the contents of the src change. For example, I could have an image src of animal.png, but I may switch the image from a tiger to an elephant.

The problem is the cache is holding onto those previous images even when they update in the background. Is there a way to force the browser to clear the image cache when the page loads. My website is coded in .html .css and .js

Wx_Trader
  • 77
  • 7
  • I don't think there's a way to clear the end user's cache, and I also *hope* there isn't. (Leave my browser alone!) The obvious solution is to change the filename, which you have full control over. (Edit: as Geshode says below, a query string at the end is probably the perfect solution. It's common to do this with CSS files, for example, to force the browser to refresh them. These query strings can easily be generated automatically.) – ralph.m Jul 07 '23 at 01:07
  • 2
    [This](https://stackoverflow.com/a/729623/9038475) might be a viable option for you. – Geshode Jul 07 '23 at 01:07
  • Can you set the Cache-Control header in the server's response? https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control – padeso Jul 07 '23 at 01:10
  • Setting the cache-control header as @padeso suggests is the neatest solution, but I would only attempt it if I could ensure that an adjusted header would only appear in responses to requests for particular images. I would want all my other responses to have the default cache behaviour. – Brett Donald Jul 07 '23 at 01:47

1 Answers1

0

You can try using Javascript to append a query string to your images as suggested.

For Example:

function call(){
  let images = document.querySelectorAll("img");
  let random_number = Math.floor(Math.random()*10000);
  
  for(image of images){
    // For images set with src attribute
    if(image.src)
    image.src+="?"+random_number;
    
    // For images set with CSS content
    if(image.style.content)
    image.style.content = "url('"+image.style.content+"?"+random_number+"')";
  }

}

//Call on load
window.onload = call;