原创

代码清除浏览器缓存或者控制文件版本

温馨提示:
本文最后更新于 2022年09月15日,已超过 561 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

页面引入js和css文件时,在最后加上时间戳

为了强制更新文件,取消浏览器缓存,防止代码修改和页面效果不同步

1.手动控制版本(添加时间戳

<link rel="stylesheet" href="ceshi.css?v=202201060936">
<script src="ceshi.js?v=202201060936"></script>

2.动态生成(添加时间戳

//第一种:单文件直接添加
<link rel="stylesheet" href="ceshi.css?v='+new Date().getTime()+'">
<script src="ceshi.js?v='+new Date().getTime()+'"></script>
//第二种:单文件js实现
<script>
	var now = new Date().getTime();
	document.write('<link href="ceshi.css?v=' + now + '" rel="stylesheet" type="text/css"/>');
    document.write('<script src="ceshi.js?v=' + now + '"><\/script\>');
</script>
//第三种:多文件自动添加随机数
//css多文件不建议都加随机数,建议用单文件添加时间戳的方式,避免ui框架加上随机数后造成的闪屏的现象.
<script>
  (function () {
    var random = Math.random();
    //处理请求JS文件缓存
    var element = document.getElementsByTagName("script");
    for (var i = 0; i < element.length; i++) {
      if (element[i].src) {
        if (element[i].src.indexOf('?') > -1) {
          element[i].src = element[i].src + '&timestreap=' + random;
        } else {
          element[i].src = element[i].src + '?timestreap=' + random;
        }
      }
    };
    //处理CSS文件缓存
    var link = document.getElementsByTagName("link");
    for (var i = 0; i < link.length; i++) {
      if (link[i].href) {
        link[i].href = link[i].href + '?timestreap=' + random;
      }
    }
  })()
</script> 

3.html5添加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" />
正文到此结束
该篇文章的评论功能已被站长关闭
本文目录