转自:
http://www.iteye.com/topic/228187
为了减小浏览器与服务器之间网络传输压力,往往对静态文件,如js,css,修饰的图片做cache,也就是给这些文件的HTTP响应头加入Expires和Cache-Control参数,并指定缓存时间,这样一定时间内浏览器就不会给服务器发出任何的HTTP请求(除了强制刷新),即使在这段时间内服务器的js或css或图片文件已经更新多次,但浏览器的数据依然是原来最能初cache的旧数据,有没有办法让浏览器拿到已经修改后的最新数据呢?
有,方法是用ajax请求服务器最新文件,并加上请求头If-Modified-Since和Cache-Control,如下:
$.ajax({
type: "GET",
url: "static/cache.js",
dataType: "text",
beforeSend :function(xmlHttp){
xmlHttp.setRequestHeader("If-Modified-Since","0");
xmlHttp.setRequestHeader("Cache-Control","no-cache");
}
});
这里用了jquery.
这样浏览器就会把最新的文件替换掉本地旧文件。
当然,这里还一个问题就是js必须知道服务器更新了那个js、css、图片,利用cookie和时间版本应该可以解决.
另,jquery自从1.2开始就有ifModified和cache参数了,不用自己加header
ifModified Boolean Default: false
Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header.
cache Boolean Default: true
Added in jQuery 1.2, if set to false it will force the pages that you request to not be cached by the browser.
$.ajax({
type: "GET",
url: "static/cache.js",
dataType: "text",
cache:false,
ifModified :true
});
另另。。加时间戳window.location=this.location.href+"#"+new Date().getTime()
4、<meta http-equiv="Pragma" contect="no-cache">是用于设定禁止浏览器从本地机的缓存中调阅页面内容,设定后一旦离开网页就无法从Cache中再调出;
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta http-equiv="Cache-Control" content="no-store"/>
<meta http-equiv="Pragma" content="no-cache"/>
<meta http-equiv="Expires" content="0"/>