zoukankan      html  css  js  c++  java
  • 用ajax清除浏览器缓存的js、css、图片等

    为了减小浏览器与服务器之间网络传输压力,往往对静态文件,如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
    });


  • 相关阅读:
    Table的基本操作
    MySQL数据库基本操作
    jmeter中服务器返回的cookies的查看
    jemeter的乱码问题
    cucumber的报告
    Cucumber的依赖
    idea里maven执行插件pom文件依赖设置
    Tomcat和jenkins的安装
    maven配置
    Ajax必知必会
  • 原文地址:https://www.cnblogs.com/luluping/p/1336944.html
Copyright © 2011-2022 走看看