Created
April 22, 2014 09:32
-
-
Save GZShi/11171877 to your computer and use it in GitHub Desktop.
超简易脚本加载
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
// 简易ajax | |
function ajax(options) { | |
var xhr = new XMLHttpRequest(); | |
xhr.open(options.type, options.url, true); | |
xhr.send(options.data || ''); | |
xhr.onreadystatechange = function() { | |
if(xhr.readyState === 4 && xhr.status === 200) { | |
(function(data) { | |
if(typeof options.success == 'function') { | |
options.success(data); | |
} else { | |
console.log(data); | |
} | |
})(xhr.responseText); | |
} | |
}; | |
} | |
// 获取本地存储 | |
function load(item) { | |
if(window['localStorage'] && window['localStorage']['getItem']) { | |
return localStorage.getItem(item); | |
} | |
} | |
// 本地存储 | |
function save(item, value) { | |
if(window['localStorage'] && window['localStorage']['setItem']) { | |
localStorage.setItem(item, value); | |
} | |
} | |
// 获取本地脚本 | |
function loadScript(files) { | |
for(var i = 0, flen = files.length; i < flen; ++i) { | |
var a = document.createElement('a'); | |
a.href = files[i]; | |
files[i] = a.pathname; | |
} | |
var newScript = new ScriptRuntime(files); | |
var fileUrl = ''; | |
for(var i = 0, flen = files.length; i < flen; ++i) { | |
fileUrl = files[i]; | |
if(fileUrl.length == 0) continue; | |
value = load(fileUrl); | |
if(!value) { | |
(function(index, url){ | |
ajax({ | |
type: 'GET', | |
url: url, | |
success: function(data) { | |
save(url, data); | |
newScript.add(url, data); | |
console.log('[AJAX][SIZE:' + data.length + '] "' + fileUrl + '"'); | |
} | |
}) | |
})(i, fileUrl); | |
} else { | |
newScript.add(fileUrl, value); | |
console.log('[CACHE][SIZE:' + value.length + '] "' + fileUrl + '"'); | |
} | |
} | |
} | |
function ScriptRuntime(dependences, tailFunction) { | |
this.dependences = []; | |
this.indexs = {}; | |
this.loadedCount = 0; | |
for(var i = 0, dlen = dependences.length; i < dlen; ++i) { | |
if(dependences[i].length > 0) { | |
this.dependences.push({ | |
'name': dependences[i], | |
'code': '', | |
'loaded': false | |
}); | |
this.indexs[dependences[i]] = i; | |
} | |
} | |
this.add = function(name, data) { | |
var index = this.indexs[name]; | |
if(typeof index == 'number') { | |
this.dependences[index].code = data; | |
this.dependences[index].loaded = true; | |
this.loadedCount += 1; | |
if(this.loadedCount == this.dependences.length) { | |
var allCode = ''; | |
for(var i = 0, len = this.dependences.length; i < len; ++i) { | |
allCode = allCode + this.dependences[i].code + ';\n'; | |
} | |
(new Function(allCode))(); | |
} | |
} | |
} | |
} | |
// 用法示例 | |
window.onload = function() { | |
loadScript(['test1.js', 'test2.js']); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment