Avoid actual image caching, not just changing the src name

Asked

Viewed 401 times

1

I have an image that loads multiple times, each time with content that won’t be reused. to this problem, I found several answers suggesting something

var d = new Date();
buff.src="carrega.php?ver="+d.getTime();

Or with random number.

others suggest:

<meta Http-Equiv="Cache-Control" Content="no-cache">
<meta Http-Equiv="Pragma" Content="no-cache">
<meta Http-Equiv="Expires" Content="0">
<meta Http-Equiv="Pragma-directive: no-cache">
<meta Http-Equiv="Cache-directive: no-cache">

Good, the second solution simply doesn’t work. And if it did it would be for the whole page and I want to disable the cache of an image only.

The first is not a solution. It returns me different images, so far ok. But, every time I upload, the image is cached, which is what I want to avoid to not load memory usage (there are many images loaded during very long usage). I also don’t want to have to recommend the user to limit the cache storage space. That wouldn’t be troubleshooting, either.

  • Only disable cache by HTTP headers

  • I tried this by disabling caching by the http headers of the image with: header("Pragma-Directive: no-cache"); header("Cache-Directive: no-cache"); header("Cache-control: no-cache"); header("Pragma: no-cache"); header("Expires: 0"); , and it doesn’t work. Keeps storing whenever the image is updated

1 answer

4


One way is via file .htaccess, adding the code:

<filesMatch "nome_da_imagem\.(jpg|png)$">
  FileETag None
  <ifModule mod_headers.c>
     Header unset ETag
     Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
     Header set Pragma "no-cache"
     Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
  </ifModule>
</filesMatch>

Will avoid caching files jpg and png with a fixed name. If only jpg, just change the regex to:

"nome_da_imagem\.jpg$"

If you want to avoid caching any file jpg:

"\.jpg$"

Testing in Chrome using the Chromecacheview app (CCV):

  1. First I’ll clear the Chrome cache and open the CCV. See that it’s empty:

inserir a descrição da imagem aqui

  1. I will open a page that contains only one image 1.jpg and update the CCV window:

inserir a descrição da imagem aqui

Note that you have cached several files (.js, .html etc.) but have not cached the image 1.jpg that has on the page.

Now I’m going to remove the code from .htaccess, clear the Chrome cache and reopen the page. When updating the CCV window, this time the image appears cached (1.jpg):

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.