Is there a way to protect clients from client-side caching?

Is it possible to control using javascript, does the browser go to the server for an image or to the browser cache? Can I make the browser make a server call if it would otherwise use a cached image? I know that I can just add a query string to my image URL, but if I understand correctly, this works because the browser sees it as a new image. I want the old image to be replaced in the cache.

+4
source share
2 answers

You can use the meta tags on the page to control the cache, set "no-cache" as follows:

<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE"> 

and

 <META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"> 

You can also set the page to "expire" at a point in the past, which theoretically forces the browser to check the latest version:

 <META HTTP-EQUIV="EXPIRES" value="some date in the past" /> 

Please note that โ€œsome date in the pastโ€ must be GMT format RFC 1123 .

Note. You can simply send them to the HTTP header: See here

Hope this helps.

+1
source

You cannot do anything similar with the standard img tag. You can create an XMLHttpRequest for the image and set the if-modified-since header. This should replace the old cache image:

 var url = "http://www.mysite.com/images/myimage.png"; var xhr = new XMLHttpRequest(); // or x-browser compat function xhr.open("GET", url, true); xhr.setRequestHeader("If-modified-since", "Thu Jan 1 00:00:00 UTC 1970"); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) document.getElementById("myImg").src = url; } xhr.send(); 
0
source

Source: https://habr.com/ru/post/1307841/


All Articles