jQuery 获取脚本
我目前一直在使用几个必须以非常特定的顺序加载的 JavaScript 库。由于 jQuery 的 getScript() 是异步的,因此它会非常快速地开始下载所有脚本,并在完成后执行它们。由于它们不按顺序执行,我从库中收到多个错误。
不幸的是我无法更改或修改任何这些库。我试图做的是使用一种下载 JavaScript 库的方法,并在回调中让它调用自身,直到完成加载所有库。
这适用于第一个文件。当第二个文件出现时,它会丢失回调内部的上下文,我无法再调用我的递归方法。
有什么想法吗?
代码的配对版本:
function loadFiles (CompletedCallback) {
var Files = getFiles(); // This is an array of js files to load
var currentFileIndex = 0;
function processFile (file) {
$.getScript(file[currentFileIndex], $.proxy(function () {
++currentFileIndex;
if (currentFileIndex === Files.length) {
CompletedCallback();
} else {
processFile(Files[currentFileIndex]);
}
}, this);
};
processFile(Files[currentFileIndex]);
};
I'm currently stuck using several JavaScript libraries that MUST load in a very specific order. Since jQuery's getScript() is asynchronous it starts downloading all of the scripts very quickly and, as they finish, executes them. Since they do not execute in order I get multiple errors coming from the libraries.
Unfortunately I cannot change or modify any of these libraries. What I'm attempting to do is use a method that downloads a JavaScript library and, in the callback, have it call itself until it's finished loading all of the libraries.
This works for the first file. When the second file comes around it loses context inside of the callback and I can't call my recursive method anymore.
Any ideas?
A paired-down version of the code:
function loadFiles (CompletedCallback) {
var Files = getFiles(); // This is an array of js files to load
var currentFileIndex = 0;
function processFile (file) {
$.getScript(file[currentFileIndex], $.proxy(function () {
++currentFileIndex;
if (currentFileIndex === Files.length) {
CompletedCallback();
} else {
processFile(Files[currentFileIndex]);
}
}, this);
};
processFile(Files[currentFileIndex]);
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不确定您的代码有什么问题,但我会这样做:
编辑,更好的版本:
或者甚至更好,如果您不关心旧浏览器或实现
Function.prototype.bind
自己(也支持绑定参数,而不仅仅是this
上下文):I'm not sure what's wrong with your code, but here's how I would do that:
edit, a nicer version:
or even nicer, if you don't care about old browsers or implement
Function.prototype.bind
yourself (with support for binding arguments too, and not just thethis
context):您可以执行同步调用,只需执行以下操作:
You can do sync calls just do this:
简单形式:
用法:
simple form:
usage: