我编写了以下内容,让我从数组中加载脚本:
scriptLoader = (function(){
var loader = function (src, handler) {
if(!self.errorstate){
var script = document.createElement("script");
script.src = src;
script.onload = script.onreadystatechange = function () {
script.onerror = loaderror(src);
script.onreadystatechange = script.onload = null;
};
var head = document.getElementsByTagName("head")[0];
(head || document.body).appendChild(script);
}
};
var loaderror = function (src) {
self.errorstate = true;
console.log('Error: '+src);
return false;
};
var self = {};
self.errorstate = false;
self.files = null;
self.callback = null;
self.go = function(){
if (self.files.length !== 0) {
loader(self.files.shift(), arguments.callee);
} else {
if (self.callback && typeof (self.callback) === 'function' && !self.errorstate) {
self.callback();
}
}
};
return self;
});
我打电话给:
var scripts = [
'js/placeholder.js',
'js/modal.js',
'js/alert.js',
'js/notafile.js'
];
loader = new scriptLoader();
loader.files = scripts;
loader.callback = alert('loaded');
loader.go();
一切似乎都正常,除了我无法让它因错误(js/notafile.js
)而中断 - 所以停止加载更多脚本并且不允许回调触发。它在控制台中显示错误消息很好,我只是找不到阻止它的好方法!