zoukankan      html  css  js  c++  java
  • 解决微信端页面文件被缓存

    一般情况

    1. 添加版本号,在静态资源文件的引用链接后面添加版本号,这样每次发布的时候更新版本号,就能让叫客户端加载新的资源文件,避免再次使用缓存的老文件,如:
      <script src="//m.test.com/build/activity/js/commons.js?v=20170608"></script>
      
    2. 文件名使用hash形式,webpack中打包文件可直接生成,这样每次打包发布的时候都会产生新的hash值,区别于原有的缓存文件:
      <script src="//m.test.com/build/activity/js/activity/201807/schoolbeauty/main.19315e5.js"></script>
      
    3. 服务器及缓存头设置,不使用缓存,如:
      location ~* ^.+.(jpg|jpeg|gif|png|ico|css|js)$ {
        root  /mnt/dat1/test/tes-app;
        #### kill cache
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
      }  
      
    4. 在html的meta标签添加缓存设置:
      <!-- cache control: no cache -->
      <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
      <meta http-equiv="Pragma" content="no-cache" />
      <meta http-equiv="Expires" content="0" />
      

    微信浏览器来啦!!!

    微信浏览器下比较特殊,这个bug一样的存在居然把入口文件html给缓存下来了,这就意味着通过版本号和hash号的形式避免缓存的方案失效了。同时html的meta设置依旧没能生效。

    1. 更改服务器配置,强制不缓存入口文件,其他静态正常缓存,比如在nginx中对静态部分如下:(据说有效,未实测)
      location / {
        root  /mnt/dat1/test/tes-app;
        index index.html index.htm;
        try_files $uri $uri/ /index.html;
        #### kill cache
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
      }
      
      location ~* ^.+.(jpg|jpeg|gif|png|ico|css|js)$ {
        root  /mnt/dat1/test/tes-app;
        access_log off;
        expires 30d;
      } 
      
    2. 通过url参数避免html文件缓存,给html文件添加版本号:(亲测有效)
      www.xxx.com/home.html?v=1.0
      
      虽说这个方式有效,但即使采用了链接后面加版本号这种方式,由于首页的地址无法修改(已经发布到内部了,不能去修改),所以入口文件被缓存在了微信本地,到后面更新文件后,只有当缓存文件失效后页面才被更新,所以在生产上并不能解决问题。

      之后在这个基础上想到了下面这个方法(将以下代码添加到文件最开头位置即可,亲测有效):

      var href = window.location.href;
      var stamp = new Date().getTime();
      if(href.indexOf("stamp=") == -1) {
       window.location.replace(href + "?stamp=" + stamp);
      }
      
    3. 避免css和js的缓存:(未使用)
      微信发现我们所请求的js和css文件在他的缓存里面有了,所以就直接打开缓存中的文件返回给了页面上,所以我们要在html文件的头部(head)处加上一些meta:
      <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
      <meta http-equiv="Pragma" content="no-cache" />
      <meta http-equiv="Expires" content="0" />
      
      因为meta只能保障js和css等资源不会被缓存,但是无法保障html不被缓存。所以,要和url参数方法于meta方法一起使用。

    补充:
    h5移动端开发 判断只能在微信浏览器打开

  • 相关阅读:
    Subsets II
    Pow(x, n)
    基本数据结构 —— 二叉搜索树(C++实现)
    基本数据结构 —— 堆以及堆排序(C++实现)
    Symmetric Tree
    Same Tree
    C++中三种传递参数方法的效率分析
    Word Search
    Subsets
    Combinations
  • 原文地址:https://www.cnblogs.com/ZerlinM/p/13689601.html
Copyright © 2011-2022 走看看