最近開(kāi)發(fā)webview嵌套開(kāi)發(fā),遇到資源重載的問(wèn)題,具體表現(xiàn)在:css緩存強(qiáng)硬,js緩存強(qiáng)硬,無(wú)法事實(shí)更新靜態(tài)資源,但若是禁止頁(yè)面使用緩存策略的話,對(duì)服務(wù)器的占用比就會(huì)提高,訪問(wèn)少的時(shí)候,還好,訪問(wèn)量幾何上升時(shí),服務(wù)器就GG了。
經(jīng)過(guò)多方查找發(fā)現(xiàn)除去glup,webpack,node,以及服務(wù)器做資源版本之外,并沒(méi)有一個(gè)簡(jiǎn)單省事的方法,但項(xiàng)目時(shí)單純的html頁(yè)面,并沒(méi)有什么框架使用,如若使用打包方式增加版本號(hào)更新緩存的話,相比較會(huì)麻煩一些,所以自己扣置了個(gè)小玩意。
由于script標(biāo)簽更新src之后并不會(huì)資源重載,所以使用了標(biāo)簽重新插入,link標(biāo)簽在更新href之后,資源會(huì)重新進(jìn)行加載,所以直接替換路徑
廢話不多說(shuō),直接上代碼:
function EditionFn (edition){
if(edition.notUrl){
edition.notUrl = edition.notUrl.split(",")
}else{
edition.notUrl = ["http:///"]
}
edition.notHtml = edition.notHtml || "http:///";
edition.isHtml = edition.isHtml || location.pathname;
if(location.pathname.indexOf(edition.notHtml) > -1 && location.pathname.indexOf(edition.isHtml) < 0){
return false
}
var cookie = document.cookie
cookie = cookie.split(";")
cookie.forEach(function(item){
item = item.replace(/\s*/g, "")
var thistime = item.split("=");
cookie[thistime[0]]= thistime[1]
})
function loadJS(script){
? ? var src = script;
? ? var script_dom = document.createElement('script');
? ? script_dom.src = src;
? ? script_dom.language = 'javascript';
? ? script_dom.type = 'text/javascript';
? ? var head = document.getElementsByTagName('head').item(0);
? ? head.appendChild(script_dom);
}
var scrUrl = [];
$('script').each(function(){
if($(this).attr("charset") == "utf-8" && $(this).attr("src") && cookie.edition && cookie.edition != edition.edition){
var src = $(this).attr("src")+ '?v=' + edition.edition;
scrUrl.push(src)
$(this).attr("src","");
}
})
if(scrUrl.length > 0){
scrUrl.forEach(function(item){
var thisType = true;
edition.notUrl.forEach(function(items){
if(item.indexOf(items) > -1){
thisType = false;
}
})
if(thisType){
loadJS(item)
}
})
}
$('link').each(function(){
if($(this).attr("type") == "text/css" && $(this).attr("href") && cookie.edition && cookie.edition != edition.edition){
var src = $(this).attr("href")+ '?v=' + edition.edition;
var thisType = true;
edition.notUrl.forEach(function(items){
if(src.indexOf(items) > -1){
thisType = false;
}
})
if(thisType){
$(this).attr("href",src)
}
}
})
var times = new Date().getTime() + 7*24*60*60*1000;
if(cookie.edition && cookie.edition != edition.edition){
document.cookie = "edition="+edition.edition+"; expires="+new Date(times)+";" ;
}else{
document.cookie = "edition="+edition.edition+"; expires="+new Date(times)+";";
}
}
調(diào)用如下:
EditionFn({
edition:edition,
notUrl:"base64.js",
notHtml: '///',
isHtml: "cssAndjsSession"
})
代表參數(shù)如下:
edition: 版本號(hào)
notUrl:不重載更新資源,默認(rèn)為空
notHtml:不重載更新路徑,默認(rèn)為空
isHtml:重載更新指定頁(yè)面(目前只能指定單個(gè)頁(yè)面,要想多個(gè)頁(yè)面自己去改代碼吧),默認(rèn)所有頁(yè)面都會(huì)更新
第一次請(qǐng)求時(shí),不會(huì)資源重載,只有版本號(hào)不符時(shí),會(huì)進(jìn)行資源重載
歡迎各位指教一二