How to clear a users image cache when the page loads

78 views Asked by At

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

1

There are 1 answers

0
Abdulrasaq On

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;