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);