1. 程式人生 > >JavaScript使用localStorage快取Js和css檔案

JavaScript使用localStorage快取Js和css檔案

對於WebApp來說,將js css檔案快取到localstorage區可以減少頁面在載入時與HTTP請求的互動次數,從而優化頁面的載入時間.特別是當移端訊號不好高延遲時優化效果還是很顯見的

下面的程式碼可以實現此功能:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title></head>
    <body>
        <!-- 1.快取css、js到LocalStorage 2.呼叫本地快取css/js拼接到HTML頁面 -->
        <script type="text/javascript">//
入口函式 if (window.localStorage) { initJs(); initCss("css", "reset.css"); } else { alert("不能使用本地快取"); addFile("http://libs.baidu.com/jquery/2.0.0/jquery.min.js", "js"); addFile("/gfdzp201508257998/Turntable/Script/whir.turntable.js", "js"); addFile(
"/gfdzp201508257998/Turntable/Style/css_whir.css", "css"); } //第一步:載入頁面js:先載入jQuery後加載使用者指令碼 function initJs() { var name = "jquery"; //儲存key的name var url = "js/jquery-1.9.1.min.js"; var xhr; var js = window.localStorage ? localStorage.getItem(name) : "";
if (js == null || js.length == 0) { if (window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } xhr.open("GET", url); xhr.send(null); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { js = xhr.responseText; localStorage.setItem(name, js); js = js == null ? "": js; addTxt(js, "js"); initTurntable(); //確保先引用Jquery } }; } else { addTxt(js, "js"); initTurntable(); } } //載入自定義指令碼 function initTurntable() { var name = "zidingyi"; var url = "js/zidingyi.js"; var xhr; var js = window.localStorage ? localStorage.getItem(name) : ""; if (js == null || js.length == 0) { if (window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } xhr.open("GET", url); xhr.send(null); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { js = xhr.responseText; localStorage.setItem(name, js); js = js == null ? "": js; addTxt(js, "js"); } }; } else { addTxt(js, "js"); } } //第二步:初始化Css function initCss(name, url) { var xhr; var css = window.localStorage ? localStorage.getItem(name) : ""; if (css == null || css.length == 0) { if (window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } xhr.open("GET", url); xhr.send(null); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { css = xhr.responseText; localStorage.setItem(name, css); css = css == null ? "": css; css = css.replace(/images\//g, "style/images/"); addTxt(css, "css"); } }; } else { css = css.replace(/images\//g, "style/images/"); addTxt(css, "css"); } } //輔助方法1:動態新增js,css檔案引用 function addFile(url, fileType) { var head = document.getElementsByTagName('HEAD').item(0); var link; if (fileType == "js") { link = document.createElement("script"); link.type = "text/javascript"; link.src = url; } else { link = document.createElement("link"); link.type = "text/css"; link.rel = "stylesheet"; link.rev = "stylesheet"; link.media = "screen"; link.href = url; } head.appendChild(link); } //輔助方法2:動態新增js,css檔案內容 function addTxt(text, fileType) { var head = document.getElementsByTagName('HEAD').item(0); var link; if (fileType == "js") { link = document.createElement("script"); link.type = "text/javascript"; link.innerHTML = text; } else { link = document.createElement("style"); link.type = "text/css"; link.innerHTML = text; } head.appendChild(link); }</script> </body> </html>

再看看封裝通用外掛方法:

/**
 * 外掛功能:使用localStorage快取js和css檔案,減少http請求和頁面渲染的時間,使用於web移動端H5頁面的製作
 * 使用方法:
 *         1.使用此外掛前,需要給外掛的pageVersion變數賦值,建議變數值由伺服器後端輸出,當需要更新客戶資源時,修改變數值即可
 *         2.載入js:由於js載入有順序要求,所以需要將後加載的指令碼作為前一個載入的回撥函式引數傳入,如:
 *           whir.res.loadJs ("jquery","TurnTable/Script/jquery.min.js",
 *                             function () {
 *                                 whir.res.loadJs(name,url,null)
 *                             });
 */
var whir = window.whir || {};
whir.res = {
    pageVersion : "",//版本,有頁面輸入,用語重新整理localStorage快取
    loadJs : function (name, url, callback) {//動態載入js檔案並快取
        if (window.localStorage) {
            var xhr;
            var js = localStorage.getItem(name);
            if (js == null || js.length == 0 || this.pageVersion != localStorage.getItem("version")) {
                if (window.ActiveXObject) {
                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                } else if (window.XMLHttpRequest) {
                    xhr = new XMLHttpRequest();
                }
                if (xhr != null) {
                    xhr.open("GET",url);
                    xhr.send(null);
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == 4 && xhr.status == 200) {
                            js = xhr.responseText;
                            localStorage.setItem(name,js);
                            localStorage.setItem("version",whir.res.pageVersion);
                            js = js == null ? "" : js;
                            whir.res.writeJs(js);
                            if (callback != null) {
                                callback();
                            }
                        }
                    }
                }
            } else {
                whir.res.writeJs(js);
                if (callback != null) {
                    callback();//回撥,執行下一個引用
                }
            }
        } else {
            whir.res.linkJs(url);
        }
    },
    loadCss : function (name,url) {
        if (window.localStorage) {
            var xhr;
            var css = localStorage.getItem(name);
            if (css == null || css.length == 0 || this.pageVersion != localStorage.getItem("version")) {
                if (window.ActiveXObject) {
                    xhr = new ActiveXObject("Microsoft.XNLHTTP");
                } else if (window.XMLHttpRequest) {
                    xhr = new XMLHttpRequest();
                }
                if (xhr != null) {
                    xhr.open("GET",url);
                    xhr.send(null);
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == 4 && xhr.status == 200) {
                            css = xhr.responseText;
                            localStorage.setItem(name,css);
                            localStorage.setItem("version",whir.res.pageVersion);
                            css = css == null ? "" : css;
                            css = css.replace(/images\//g,"style/images/");//css裡的圖片路徑需要單獨處理
                            whir.res.writeCss(css);
                        }
                    }
                }
            } else {
                css = css.replace(/images\//g,"style/images/");//css裡的圖片路徑需要單獨處理
                whir.res.writeCss(css);
            }
        } else {
            whir.res.linkCss(url);
        }
    },
    writeJs : function (text) {//往頁面寫入js\指令碼
        var head = document.getElementsByTagName('HEAD').item(0);//獲取head
        var link = document.createElement("script");
        link.type = "text/javascript";
        link.innerHTML = text;
        head.appendChild(link);
    },
    writeCss : function (text) {//往頁面寫入css樣式
        var head = document.getElementsByTagName("HEAD").item(0);
        var link = document.createElement("style");
        link.type = "text/css";
        link.innerHTML = text;
        head.appendChild(link);
    },
    linkJs : function (url) {//往頁面引入js
        var head = document.getElementsByTagName('HEAD').item(0);//獲取head
        var link = documenr.createElement("script");
        link.type = "text/javascript";
        link.src = url;
        head.appendChild(link);
    },
    linkCss : function (url) {//往頁面引入css
        var head = document.getElementsByTagName('HEAD').item(0);  
        var link = document.createElement("link");  
        link.type = "text/css";  
        link.rel = "stylesheet";  
        link.rev = "stylesheet";  
        link.media = "screen";  
        link.href = url;  
        head.appendChild(link);
    }
};

  呼叫該外掛:

<script type="text/javascript" src="fengzhuang.js"></script>
<script type="text/javascript">
//入口函式
whir.res.pageVersion = "1002"; //頁面版本,用於檢測是否需要更新快取
whir.res.loadJs("jquery", "js/jquery-1.9.1.min.js",
function () {
whir.res.loadJs("zidingyi", "js/zidingyi.js", null);
});
whir.res.loadCss("css", "reset.css", null);
</script>

電腦端使用localstorage是測試沒有問題的,但是用android的apk打包之後,導致localstorage失效,無法進行快取,查閱資料之後,得知解決方法:

安卓程式碼:

mWebView.getSettings().setDomStorageEnabled(true);   
mWebView.getSettings().setAppCacheMaxSize(1024*1024*8);  
String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();  
mWebView.getSettings().setAppCachePath(appCachePath);  
mWebView.getSettings().setAllowFileAccess(true);  

mWebView.getSettings().setAppCacheEnabled(true);

另外:Web移動端使用localStorage快取Js和css檔案 | 強制不要快取

1.儘量不把js放在onload事件中,而是放在由使用者主動觸發的事件
2.加時間戳,時間不同則會載入js而非使用快取

強制不要快取:
<meta http-equiv=Cache-Control content=no-cache /> 
必須結合其他:
<!-- 禁止瀏覽器從本地快取中調閱頁面。--> 
<meta http-equiv="pragram" content="no-cache"> 
<!--網頁不儲存在快取中,每次訪問都重新整理頁面。--> 
<meta http-equiv="cache-control" content="no-cache, must-revalidate"> 
<!--同上面意思差不多,必須重新載入頁面--> 
<meta http-equiv="expires" content="0"> 
<!--網頁在快取中的過期時間為0,一旦網頁過期,必須從伺服器上重新訂閱--> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

 

轉自:https://blog.csdn.net/qq_29132907/article/details/79390605

https://www.cnblogs.com/wwdxf/p/6646649.html

https://www.cnblogs.com/zyjzz/p/6973608.html