最近因为在做前端开发的相关工作,每次发布新版本以后,不到5分钟,测试童鞋一个接一个的抱怨说BUG根本就没有修改,这个时候你说的最多的话就是“清缓存!!清页面缓存!!你没有清缓存!!你清理了页面缓存就对了的!!?”,有木有很头大的感觉,其实资源缓存对提升软件性能还是有很大的作用的。
不让页面缓存这些文件方法其实很多,但我们经常用的就这几样,这里我用到的是在资源后面加版本号来实现资源不缓存的功能,具体代码如下:
/**
* 给页面引用的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();
}
调用方法:
<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>