Is it possible to control with javascript whether a browser goes to the server for an image or to the browser cache? Can I force the browser to make a server call when it would otherwise use a cached image? I know I can simply append a query string to my image url, but, if I understand correctly, that works because the browser sees that as a new image. I want the old image to be replaced in the cache.
+1
A:
You can't do anything like this with a standard img
tag. You could create an XMLHttpRequest for the image and set the if-modified-since
header. This should replace the old image in the cache:
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();
Andy E
2010-04-23 23:08:29
Thanks Andy E's head. What about simply doing this: document.getElementById("myImg").src = url
morgancodes
2010-04-23 23:59:57
@morgancodes: When you set the image `src` to a url, it will use the browser default caching methods and retrieve the currently cached image. There are no ways to set request headers or any other HTTP related options when making the request. The method in my answer forces the browser to download a new copy of the image and keep it in the cache, then it switches an image element to that newly cached version.
Andy E
2010-04-24 09:16:32
Cool. Thanks. Gonna give it a try now.
morgancodes
2010-04-27 16:50:24
Hmmm. Doesn't seem to have worked. I see the header go through in firebug, but see the url still cached from before when I look at it via about:cache.
morgancodes
2010-04-27 23:05:29
+1
A:
You can use meta tags on the page for cache-control, set to "no-cache" like so:
<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 in theory will cause the browser to check for the newest version:
<META HTTP-EQUIV="EXPIRES" value="some date in the past" />
Note, that "some date in the past" must be GMT in RFC 1123 format.
Note, you could just send these in the HTTP header itself: See Here
Hope this helps.
MisterMister
2010-04-24 01:59:55
Also, I'm gonna start a programming themed ska-core band called NO CACHE...
MisterMister
2010-04-24 07:48:02