Last active
December 28, 2015 23:18
-
-
Save StuPig/7577498 to your computer and use it in GitHub Desktop.
require localStorage plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* USAGE: | |
* 外部定义全局变量 RSINFO = { 'path': 'version' } | |
*/ | |
(function (win) { | |
var rslist, | |
RSLIST_KEY = 'rslist', | |
RSINFO = win.RSINFO || {}, | |
isLocalStorageSupported = (function() { | |
var localStorageName = 'localStorage'; | |
try { return (localStorageName in win && win[localStorageName]) } | |
catch(err) { return false } | |
}) (), | |
localStorage = win.localStorage, | |
loadThroughXHR = function(url, callback) { | |
var xhr = new XMLHttpRequest(); | |
xhr.open('GET', url, true); | |
xhr.onreadystatechange = function(e) { | |
// 不处理错误,有错误就抛出 | |
if (xhr.readyState === 4) { | |
callback( xhr.responseText ); | |
} | |
} | |
xhr.send(null); | |
}, | |
parseName = function(name) { | |
var modName, ext, | |
index = name.lastIndexOf('.'); | |
modName = name.substring(0, index); | |
ext = name.substring(index + 1); | |
return { | |
moduleName: modName, | |
ext: ext | |
}; | |
}, | |
updateLocalStorage = function(url, content) { | |
rslist[url] = { | |
v: RSINFO[url], | |
l: content.length | |
}; | |
try { | |
localStorage.setItem(url, content); | |
localStorage.setItem(RSLIST_KEY, JSON.stringify( rslist ) ); | |
} catch(err) {} | |
}; | |
// 合法性校验,清空过期和无效的js文件 | |
// RSINFO 由后端直接吐到页面上 | |
(function() { | |
if (!!RSINFO && isLocalStorageSupported) { | |
var k, v, isFresh; | |
rslist = JSON.parse(localStorage.getItem(RSLIST_KEY)) || {}; | |
for (k in RSINFO) { | |
isFresh = RSINFO.hasOwnProperty(k) && (rslist.hasOwnProperty(k) | |
// 判断版本号一致 | |
&& (v = RSINFO[k]) == rslist[k].v | |
// 校验文件长度一致 | |
&& (localStorage[k].length == rslist[k].l)); | |
if (!isFresh) { | |
delete rslist[k]; | |
localStorage.removeItem(k); | |
} | |
} | |
localStorage.setItem(RSLIST_KEY, rslist); | |
} | |
}) (); | |
define({ | |
load: function(name, req, load, config) { | |
if (config.isBuild) { | |
load(); | |
return; | |
} | |
var cached, | |
parsed = parseName(name), | |
url = req.toUrl(name); | |
if (isLocalStorageSupported) { | |
cached = localStorage[url]; | |
if (cached) { | |
load.fromText(cached); | |
} else { | |
loadThroughXHR(url, function(content) { | |
if (parsed.ext === 'js') | |
content += '\n //@ sourceURL=' + name; | |
load.fromText(content); | |
updateLocalStorage(url, content); | |
}); | |
return; | |
} | |
} | |
req([name], function (content) { | |
load(content); | |
}); | |
} | |
}); | |
}) (window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment