zoukankan      html  css  js  c++  java
  • 利用本地存储,保存js文件

    var ScriptStorage = function (url) {
        this.url = url;
        this.storageName = 'script-' + url.split('?')[0];
        this.init();
    }
    
    ScriptStorage.prototype = {
        init: function () {
            if(this.hasStorage){
                var storage = this.storage.get(this.storageName);
                if(storage && storage.url === this.url){
                    this.scriptHandle(storage.script, 0);
                }else{
                    this.xhr(this.url, this.scriptHandle.bind(this));
                }
            }else{
                var script = this.createElement('script',{"src": this.url});
                document.body.appendChild(script);
            }
        },
        hasStorage: (function(){
            var test = 'test';
            try {
                localStorage.setItem(test, test);
                localStorage.removeItem(test);
                return true;
            } catch(e) {
                return false;
            }
        }()),
        scriptHandle: function (data, restorage) {
            if(data){
                var script = this.createElement('script');
                script.innerHTML = data;
                document.body.appendChild(script);
                var storageData = {
                    url: this.url,
                    script: data
                }
                if(restorage){
                    this.storage.set(this.storageName, storageData);
                }
            }
        },
        createElement: function (tag, option) {
            var el = document.createElement(tag);
            for (var i in option) {
                if(option.hasOwnProperty(i)){
                    el.setAttribute(i, option[i]);
                }
            }
            return el;
        },
        storage: {
            get: function (key) {
                return JSON.parse(window.localStorage.getItem(key));
            },
            set: function (key, value) {
                return window.localStorage.setItem(key, JSON.stringify(value));
            }
        },
        xhr: function (url, callback) {
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status ==200) {
                    callback(xhr.responseText, !0);
                }
            }
            xhr.open('GET', url, true);
            xhr.send(null);
        }
    }
    
    var scriptUrl = 'test.js?version=1.0.0';
    var storageScript = new ScriptStorage(scriptUrl);
  • 相关阅读:
    【面试】Java基础
    GC
    【面试】JVM
    Spooling技术
    数据结构之 平衡二叉树
    二叉树应用
    LINUX设备驱动模型之class
    RTC(x86)
    微内核和单内核
    Linux内核的五大模块
  • 原文地址:https://www.cnblogs.com/childsplay/p/5028502.html
Copyright © 2011-2022 走看看