我正在尝试编写一个超简单的解决方案来异步加载一堆JS文件.到目前为止,我有以下脚本.但是,当脚本未实际加载时,有时会调用回调,这会导致找不到变量错误.如果我刷新页面有时它只是工作,因为我猜文件是直接来自缓存,因此比调用回调更快,这是非常奇怪的?
var Loader = function () {
}
Loader.prototype = {
require: function (scripts, callback) {
this.loadCount = 0;
this.totalRequired = scripts.length;
this.callback = callback;
for (var i = 0; i < scripts.length; i++) {
this.writeScript(scripts[i]);
}
},
loaded: function (evt) {
this.loadCount++;
if (this.loadCount == this.totalRequired && typeof this.callback == 'function') this.callback.call();
},
writeScript: function (src) {
var self = this;
var s = document.createElement('script');
s.type = "text/javascript";
s.async = true;
s.src = src;
s.addEventListener('load', function (e) { self.loaded(e); …Run Code Online (Sandbox Code Playgroud)