开发者

Is there a client-side way to prevent an image from being cached?

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开发者_Go百科 browser sees that as a new image. I want the old image to be replaced in the cache.


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.


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜