遇到一個(gè)項(xiàng)目栗柒,甲方對(duì)頁面打開時(shí)間要求特別高震叮,于是萌生出把資源緩存到本地的想法。本地儲(chǔ)存數(shù)據(jù)用的是localStorage农尖,摸索了一下屉符,便出現(xiàn)了下面的js:
//localFile.js
//版本控制
var script = document.getElementsByTagName("script");
for (var i = 0; i < script.length; i++) {
if (script[i].getAttribute("version")) {
if (script[i].getAttribute("version") != localStorage["version"]) {
localStorage.clear();
localStorage["version"] = script[i].getAttribute("version");
}
}
}
//js
function loadJs(jsUrl) {
if(!localStorage[jsUrl]){
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET",jsUrl,false);
xmlhttp.send();
localStorage[jsUrl] = xmlhttp.responseText;
}
return localStorage[jsUrl]
}
//img
function loadImg(img) {
if (img.getAttribute("lsrc")) {
if (!localStorage[img.getAttribute("lsrc")]) {
var x = new XMLHttpRequest();
x.responseType = "blob";
x.open("get", img.getAttribute("lsrc"), true);
x.onreadystatechange = function () {
if (x.readyState == 4) {
var reader = new FileReader();
reader.readAsDataURL(x.response);
reader.onload = function () {
localStorage[img.getAttribute("lsrc")] = this.result;
img.src = this.result;
}
}
}
x.send();
}
else {
img.src = localStorage[img.getAttribute("lsrc")];
}
}
}
//CSS
function loadCss(url) {
if(!localStorage[url]){
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET",url,false);
xmlhttp.send();
localStorage[url] = xmlhttp.responseText;
}
var s = document.createElement("style");
s.innerHTML = localStorage[url];
document.getElementsByTagName("head")[0].appendChild(s)
}
調(diào)用方法:
引入js:
<script src="js/localFile.js" version=12></script>
version為版本號(hào)剧浸,當(dāng)版本號(hào)改變的時(shí)候,js會(huì)清空localStorage矗钟,執(zhí)行的時(shí)候會(huì)重新載入全部資源唆香。
載入js:
<script>eval(loadJs("js/vue.min.js"));</script>
載入css:
<script>loadCss("style.css")</script>
載入圖片
< img lsrc="img/top.png" src="" onerror="loadImg(this)" class="top" >
圖片src為空,真實(shí)地址寫在lsrc屬性里吨艇。當(dāng)圖片讀取""地址的時(shí)候躬它,會(huì)出錯(cuò),調(diào)用onerror從而執(zhí)行函數(shù)載入圖片數(shù)據(jù)东涡。
更加喪心病狂
<script version=12>//js/localFile.js
var script = document.getElementsByTagName("script");
for (var i = 0; i < script.length; i++){
if (script[i].getAttribute("version")) {
if (script[i].getAttribute("version") != localStorage["version"]) {
localStorage.clear();
localStorage["version"] = script[i].getAttribute("version");
}
}
}
if(!localStorage["js/localFile.js"]){
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","js/localFile.js",false);
xmlhttp.send();
localStorage["js/localFile.js"] = xmlhttp.responseText;
}
eval(localStorage["js/localFile.js"]);
</script>
把這個(gè)js也寫入localStorage冯吓,記得這個(gè)要優(yōu)先執(zhí)行~
實(shí)測(cè):