var require = (function () {
var head = document.getElementsByTagName('head')[0];
function load (url,callback) {
var node,type = url.substr(url.lastIndexOf('.') + 1).toLowerCase();
if(type == 'css'){
node = document.createElement('link');
node.href = url;
node.rel = 'stylesheet';
node.type = 'text/css';
}else{
node = document.createElement('script');
node.src = url;
node.type = 'text/javascript';
}
if(typeof callback == 'function'){
if (!node.readyState) {
node.onload = callback;
} else {
node.onreadystatechange = function () {//IE
if (this.readyState == 'loaded' || this.readyState == 'complete') {
this.onreadystatechange = null;
callback();
}
};
}
}
head.appendChild(node);
}
return function (path, callback) {
if(!path || path.length === 0){
throw new Error('param "path" is required !');
}
if(typeof path === 'string'){
path = [path];
}
load(path.shift(),finish);
function finish () {
if (!path.length) {
typeof callback === 'function' && callback();
}else{
load(path.shift(),finish);
}
}
}
}) ();
require(['js/test1.js','css/css1.css', 'lib/jquery3.1.js', 'js/test2.js', 'js/test3.js'], function () {
console.log('加载完毕');
});
Firefox, Opera, Chorme 和 Safari 3+会在<script>节点接收完成之后发出一个 load 事件。你可以监听这一事件,得到脚本加载完毕的通知。
Internet Explorer 支持另一种实现方式,它发出一个 readystatechange 事件。<script>元素有一个 readyState属性,它的值随着下载外部文件的过程而改变。
readyState 有五种取值:“uninitialized”默认状态、“loading”下载开始、“loaded”下载完成、“interactive”下载完成但尚不可用、“complete”所有数据已经准备好
微软文档上说,在<script>元素的生命周期中,readyState 的这些取值不一定全部出现,但并没有指出哪些取值总会被用到。实践中,我们最感兴趣的是“loaded”和“complete”状态。
Internet Explorer 对这两个readyState 值所表示的最终状态并不一致,有时<script>元素会得到“loader”却从不出现“complete”,但另外一些情况下出现“complete”而用不到“loaded”。
最安全的办法就是在 readystatechange 事件中检查这两种状态,并且当其中一种状态出现时,删除 readystatechange 事件句柄(保证事件不会被处理两次)。