jQuery getScript [英] jQuery getScript

查看:74
本文介绍了jQuery getScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用几个必须以非常特定的顺序加载的JavaScript库。由于jQuery的getScript()是异步的,因此它可以非常快速地下载所有脚本,并在完成后执行它们。由于它们没有按顺序执行,因此我从库中获得了多个错误。

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.

不幸的是,我无法更改或修改任何这些库。我试图做的是使用一种下载JavaScript库的方法,并在回调中让它调用自己,直到它完成加载所有库。

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.

任何想法?

代码的配对版本:

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 not sure what's wrong with your code, but here's how I would do that:

function loadOrdered(files, callback) {
   $.getScript(files.shift(), function() {
       files.length
          ? loadOrdered(files, callback)
          : callback();
   });
}

编辑,更好的版本:

function loadOrdered(files, callback) {
   $.getScript(files.shift(), files.length
       ? function(){loadOrdered(files, callback);}
       : callback
   );
}

甚至更好,如果您不关心旧浏览器或实施 Function.prototype.bind 你自己(也支持绑定参数,而不仅仅是这个上下文):

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 the this context):

function loadOrdered(files, callback) {
   $.getScript(files.shift(), files.length
       ? loadOrdered.bind(null, files, callback)
       : callback
   );
}

这篇关于jQuery getScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆