給引入頁面的js和css資源加上版本號,防止瀏覽器緩存資源


  最近因為在做前端開發的相關工作,每次發布新版本以后,不到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>

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM