我正在尝试编写一个超简单的解决方案来异步加载一堆 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); }, false);
var head = document.getElementsByTagName('head')[0];
head.appendChild(s);
}
}
有没有办法测试 JS 文件是否已完全加载,而不是在实际的 JS 文件本身中放置一些东西,因为我想使用相同的模式来加载我无法控制的库(GMaps 等)。
调用代码,就在标签之前。
var l = new Loader();
l.require([
"ext2.js",
"ext1.js"],
function() {
var config = new MSW.Config();
Refraction.Application().run(MSW.ViewMapper, config);
console.log('All Scripts Loaded');
});
感谢您的帮助。
最佳答案
以防万一你觉得这很有用,我创建了一个异步实用程序库,可以让你将上面的代码编写为:
var Loader = function () {}
Loader.prototype = {
require: function (scripts, callback) {
async.map(scripts, this.writeScript, callback);
},
writeScript: function(src, callback) {
var s = document.createElement('script');
s.type = "text/javascript";
s.src = src;
s.addEventListener('load', function (e) { callback(null, e); }, false);
var head = document.getElementsByTagName('head')[0];
head.appendChild(s);
}
}
如果您正在进行大量异步调用,它有一些非常强大的功能:)
关于javascript - 使用回调异步加载 JavaScript 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3032721/