1. 程式人生 > >快取載入 新思路 localStorage

快取載入 新思路 localStorage

 JS 丟在Html 進行非同步多方載入,替代 JS+CSS  Md5 值 (程式碼是微信的哦) JS 丟在Html 進行非同步多方載入,替代 JS+CSS  Md5 值 (程式碼是微信的哦)


var Loader = (function () {
        function Loader(options) {
            this.options = options;
            if (this.options.stylesheets) {
                for (var i = 0; i < this.options.stylesheets.length; i++) {
                    this.load('css', this.options.stylesheets[i]);
                }
            }

            if (this.options.scripts) {
                for (var j = 0; j < this.options.scripts.length; j++) {
                    this.load('js', this.options.scripts[j]);
                }
            }
        }

        Loader.prototype.load = function (type, obj) {
            var _this = this;
            var fileUrl = obj.isAbsolute ? obj.file : _this.options.baseUrl + obj.file;
            if (window.localStorage) {
                // 判斷 localStorage 中是否已經有快取
                var hasLocal = typeof localStorage[obj.key] !== "undefined";

                //有快取且版本相等
                if (hasLocal && JSON.parse(localStorage[obj.key])["ver"] === obj.file) {
                    //設為已載入
                    obj.isLoad = true;

                    this.append(type, obj.file, 'inline');

                } else {
                    //版本號不相等
                    //清空 localstorage
                    localStorage.removeItem(obj.key);

                    //載入
                    this.requestResource(fileUrl, function (url, content) {
                        //設為已載入
                        obj.isLoad = true;

                        if (type === "css") {
                            content = content.replace(/(?:url\('?"?(?!data)(?!http)(.*?)'?"?\))/g, 'url("' + url.substring(0, url.lastIndexOf('/')) + '/$1")');
                        }

                        //儲存到 localStorage 中
                        localStorage[obj.key] = JSON.stringify({
                            ver: obj.file,
                            data: content
                        });

                        //append
                        _this.append(type, obj.file, 'inline');
                    })
                }
            } else {
                //不支援 localStorage, 用傳統的方式載入
                this.append(type, obj.file, 'url', fileUrl);
            }
        };

        // 插入資源
        // fileExtension: css/js
        // file: scripts/main_xxx.js
        // loadtype: inline/url
        // content:  inline 時, 需要插入的內容, url 時為 需要請求的完整 URL
        Loader.prototype.append = function (fileExtension, file, loadType, content) {
            if (fileExtension === "js") {
                if (loadType == "inline") {
                    //for 判斷檔案是否載入好
                    for (var i = 0; i < this.options.scripts.length; i++) {
                        var item = this.options.scripts[i];
                        if (item.isLoad && !item.isAppended) {
                            var s = document.createElement('script');
                            s.innerHTML = JSON.parse(window.localStorage[item.key])['data'];
                            document.body.appendChild(s);
                            item.isAppended = true;
                        } else if (!item.isLoad) {
                            break;
                        }
                    }
                } else if (loadType === 'url') {
                    var head = document.getElementsByTagName("body")[0] || document.documentElement;
                    var script = document.createElement("script");
                    script.src = content;
                    head.appendChild(script);
                }
            } else if (fileExtension === "css") {
                if (loadType == "inline") {
                    for (var i = 0; i < this.options.stylesheets.length; i++) {
                        var item = this.options.stylesheets[i];
                        if (item.isLoad && !item.isAppended) {
                            var s = document.createElement('style');
                            s.innerHTML = JSON.parse(window.localStorage[item.key])['data'];
                            document.head.appendChild(s);
                            item.isAppended = true;
                        } else if (!item.isLoad) {
                            break;
                        }
                    }
                } else if (loadType === 'url') {
                    var s = document.createElement('link');
                    s.href = content;
                    document.head.appendChild(s);
                }
            }
        };

        Loader.prototype.requestResource = function (url, success, error) {
            var request = new XMLHttpRequest();
            request.open('GET', url, true);

            request.onload = function () {
                if (request.status >= 200 && request.status < 400) {
                    var resp = request.responseText;
                    success(url, resp)
                } else {
                    if (typeof error === 'function') {
                        error(url);
                    }
                }
            };
            request.send();
        };

        return Loader;

    })();

    //baseUrl 檔案
    //key 為在 LocalStorage 中的 key 名稱
    //version 為內容名稱,同步也是 content 中儲存的
    var resource = {
        baseUrl: "https://wximg.qq.com/mmsearch/h5/dist/",
        stylesheets: [
//            {
//                key: "20170101-mmsearch-wxindex-style-index",
//                file: "wxindex/wxindex.css?v=1",
//                isAbsolute: false
//            }
        ],
        scripts: [
            {
                key: "20170101-mmsearch-wxindex-common.js",
                file: "wxindex/wxindex-common.js?v=2",
                isAbsolute: false
            },
            {
                key: "20170101-mmsearch-wxindex-detail.min.js",
                file: "wxindex/detail.min.js?v=5",
                isAbsolute: false
            }
        ]
    };
    var loader = new Loader(resource);
JS 丟在Html 進行非同步多方載入,替代 JS+CSS Md5 值 (程式碼是微信的哦) var Loader = (function () { function Loader(options) { this.options = options; if (this.options.stylesheets) { for (var i = 0; i < this.options.stylesheets.length; i++) { this.load('css', this.options.stylesheets[i]); } } if (this.options.scripts) { for (var j = 0; j < this.options.scripts.length; j++) { this.load('js', this.options.scripts[j]); } } } Loader.prototype.load = function (type, obj) { var _this = this; var fileUrl = obj.isAbsolute ? obj.file : _this.options.baseUrl + obj.file; if (window.localStorage) { // 判斷 localStorage 中是否已經有快取 var hasLocal = typeof localStorage[obj.key] !== "undefined"; //有快取且版本相等 if (hasLocal && JSON.parse(localStorage[obj.key])["ver"] === obj.file) { //設為已載入 obj.isLoad = true; this.append(type, obj.file, 'inline'); } else { //版本號不相等 //清空 localstorage localStorage.removeItem(obj.key); //載入 this.requestResource(fileUrl, function (url, content) { //設為已載入 obj.isLoad = true; if (type === "css") { content = content.replace(/(?:url\('?"?(?!data)(?!http)(.*?)'?"?\))/g, 'url("' + url.substring(0, url.lastIndexOf('/')) + '/$1")'); } //儲存到 localStorage 中 localStorage[obj.key] = JSON.stringify({ ver: obj.file, data: content }); //append _this.append(type, obj.file, 'inline'); }) } } else { //不支援 localStorage, 用傳統的方式載入 this.append(type, obj.file, 'url', fileUrl); } }; // 插入資源 // fileExtension: css/js // file: scripts/main_xxx.js // loadtype: inline/url // content: inline 時, 需要插入的內容, url 時為 需要請求的完整 URL Loader.prototype.append = function (fileExtension, file, loadType, content) { if (fileExtension === "js") { if (loadType == "inline") { //for 判斷檔案是否載入好 for (var i = 0; i < this.options.scripts.length; i++) { var item = this.options.scripts[i]; if (item.isLoad && !item.isAppended) { var s = document.createElement('script'); s.innerHTML = JSON.parse(window.localStorage[item.key])['data']; document.body.appendChild(s); item.isAppended = true; } else if (!item.isLoad) { break; } } } else if (loadType === 'url') { var head = document.getElementsByTagName("body")[0] || document.documentElement; var script = document.createElement("script"); script.src = content; head.appendChild(script); } } else if (fileExtension === "css") { if (loadType == "inline") { for (var i = 0; i < this.options.stylesheets.length; i++) { var item = this.options.stylesheets[i]; if (item.isLoad && !item.isAppended) { var s = document.createElement('style'); s.innerHTML = JSON.parse(window.localStorage[item.key])['data']; document.head.appendChild(s); item.isAppended = true; } else if (!item.isLoad) { break; } } } else if (loadType === 'url') { var s = document.createElement('link'); s.href = content; document.head.appendChild(s); } } }; Loader.prototype.requestResource = function (url, success, error) { var request = new XMLHttpRequest(); request.open('GET', url, true); request.onload = function () { if (request.status >= 200 && request.status < 400) { var resp = request.responseText; success(url, resp) } else { if (typeof error === 'function') { error(url); } } }; request.send(); }; return Loader; })(); //baseUrl 檔案 //key 為在 LocalStorage 中的 key 名稱 //version 為內容名稱,同步也是 content 中儲存的 var resource = { baseUrl: "https://wximg.qq.com/mmsearch/h5/dist/", stylesheets: [ // { // key: "20170101-mmsearch-wxindex-style-index", // file: "wxindex/wxindex.css?v=1", // isAbsolute: false // } ], scripts: [ { key: "20170101-mmsearch-wxindex-common.js", file: "wxindex/wxindex-common.js?v=2", isAbsolute: false }, { key: "20170101-mmsearch-wxindex-detail.min.js", file: "wxindex/detail.min.js?v=5", isAbsolute: false } ] }; var loader = new Loader(resource);