我想通过另一个JavaScript文件导入我的外部JavaScript文件,而不是搞乱我的HTML文件,就像@import在css中一样.
在几个网站上,包括StackOverflow本身,我注意到在DOM上添加脚本标签可以解决这个问题; 但是,这是异步完成的,而我的文件顺序很重要 - 例如,第二个文件可能依赖于列表中的第一个文件.比如说,首先加载jQuery然后加载它的依赖项(插件等),依赖项可能会提前完成加载并因为jQuery尚不存在而抛出错误.
因此,这似乎不是一种选择.如何从另一个JavaScript文件中同步加载JavaScript文件?
您无法从JS中同步加载JS文件.
但是你可以做的是实现一个加载器队列,如下所示:
function ScriptLoader(queue) {
this.started = false;
this.queue = queue || [];
this.currentIndex = 0;
var self = this;
this.next = function() {
if(self.currentIndex == self.queue.length) return;
self.load(self.queue[self.currentIndex]);
self.currentIndex++;
};
this.load = function(dest) {
var s = document.createElement('script');
s.src = dest;
document.getElementsByTagName('head')[0].appendChild(s);
s.onload = self.next;
if('onreadystatechange' in s) {
s.onreadystatechange = function () {
if (this.readyState == 'complete') {
self.next();
}
}
}
};
}
ScriptLoader.prototype.start = function() {
if(!this.started) {
this.next();
this.started = true;
}
};
var loader = new ScriptLoader(['https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js', 'http://widgets.twimg.com/j/2/widget.js']);
loader.start();
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,jQuery首先加载,然后加载jQuery UITwitter JS小部件.:)
| 归档时间: |
|
| 查看次数: |
1009 次 |
| 最近记录: |