给引入页面的js和css资源加上版本号,防止浏览器缓存资源

  最近因为在做前端开发的相关工作,每次发布新版本以后,不到5分钟,测试童鞋一个接一个的抱怨说BUG根本就没有修改,这个时候你说的最多的话就是“清缓存!!清页面缓存!!你没有清缓存!!你清理了页面缓存就对了的!!😂”,有木有很头大的感觉,其实资源缓存对提升软件性能还是有很大的作用的。

  不让页面缓存这些文件方法其实很多,但我们经常用的就这几样,这里我用到的是在资源后面加版本号来实现资源不缓存的功能,具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
 * 给页面引用的css和js加上版本号
 * @param {Object} config 配置
 */
function resource_loader(config) {
    this.css = config.css;
    this.scripts = config.scripts;
    this.head = document.getElementsByTagName('head')[0];
    //默认版本号采用时间戳,也可以自定义版本号
    this.v = '?v=' + new Date().getTime();
 
    this.load = function() {
        this.loadCSS();
        this.loadScript();
    }
     
    //加载css引用
    this.loadCSS = function() {
        var that = this;
        this.css.forEach(function(csslink) {
            var link = document.createElement("link");
            link.type = "text/css";
            link.rel = "stylesheet";
            link.href = csslink + this.v;
            this.head.appendChild(link);
        });
    }
     
    //加载js引用
    this.loadScript = function() {
        var that = this;
        this.scripts.forEach(function(scriptlink) {
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = scriptlink + this.v;
            this.head.appendChild(script);
        });
    }
    this.load();
}

  调用方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
<script type="text/javascript">
            $(function() {
                resource_loader({
                    css: [
                        'content/styles/common_page.css'
                    ],
                    scripts: [
                        'http://res.wx.qq.com/open/js/jweixin-1.4.0.js',
                        'content/scripts/utils/wx_config.js'
                    ]
                });
            })
        </script>

  

 

posted @   大师兄丶  阅读(2747)  评论(1编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示