论坛首页 Web前端技术论坛

用ajax清除浏览器缓存的js、css、图片等

浏览 11060 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-08-15  

 为了减小浏览器与服务器之间网络传输压力,往往对静态文件,如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和时间版本应该可以解决.

   发表时间:2008-08-18  
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
  });

0 请登录后投票
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics