Is there a way to force browsers to refresh/download images?

Viewed 89323

I have a problem where users are reporting that their images aren't being uploaded and the old ones are still there. On closer inspection the new images are there, they just have the same name as the old one. What I do on the upload is that I rename the images for SEO purposes. When they delete an image the old index becomes available and is reused. Therefore it has the same image name.

Is there a way to (i thought maybe there might be a meta tag for this) to tell the browser to not use its cahce?

The better answer is to rename the image to something totally new. I will get working on that but in the mean time is the quick solution while I work on the bigger problem.

14 Answers

My favourite PHP solution:

<img src="<?php echo "image.jpg" . "?v=" . filemtime("image.jpg"); ?>" />

every change of file "create" a new version of the file

Another powerfull solution:

<img src="image.png?v=<?php echo filemtime("image.png"); ?>" />

This print the "last-modification-timestamp" on the path.

New version --> Download new image

Same version --> Take cache's one

in PHP you can use this trick

<img src="image.png?<?php echo time(); ?>" />

The time() function show the current timestamp. Every page load is different. So this code deceive the browser: it read another path and it "think" that the image is changed since the user has visited the site the last time. And it has to re-download it, instead of use the cache one.

It sounds like the concern is more about the primary user seeing their new image than cache being disabled entirely? If that's the case, you can do the following:

var headers = new Headers()
headers.append('pragma', 'no-cache')
headers.append('cache-control', 'no-cache')

var init = {
  method: 'GET',
  headers: headers,
  mode: 'no-cors',
  cache: 'no-cache',
}

fetch(new Request('path/to.file'), init)

If you do this after a new image is uploaded, the browser should see those headers and make a call to the backend, skipping the cache. The new image is now in cache under that URL. The primary user will see the new image, but you still retain all the benefits of caching. Anyone else viewing this image will see updates in a day or so once their cache invalidates.

If the concern was more about making sure all users see the most up to date version, you would want to use one of the other solutions.

I had come up with this issue some times ago. And I was getting data through JSON in AJAX. So what I did is, I just added a Math.random() Javascript function and It worked like a charm. The backend I used was a flask.

<img class="card-img-top w-100 d-block" style="padding:30px;height:400px" src="static/img/${data.image}?${Math.random()} ">

Related