1

对于我的 jQuery 应用程序,我想实现延迟加载。因此我创建了一个对象,其中包含我所有的 jqXHR 承诺。

当我现在将所有内容组合成一个声明时

var resultset = new Object();
resultset.one = $.getScript('http://......');
resultset.two = $.getScript('http://......');

$.when(resultset.one,resultset.two).then(
function(){ alert('success')},
function(){alert('failure')}
);

然后它总是进入错误状态。我不知道为什么,因为 js 调试器告诉,所有请求都很好(状态 200)。

JQ API 文档说明以下内容将起作用:

$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
  .then(myFunc, myFailure);

有任何想法吗?

4

3 回答 3

2

您可以使用带有 getScript() 的 Promise 并等到所有脚本都加载完毕,例如:

$.when(
    $.getScript( "/mypath/myscript1.js" ),
    $.getScript( "/mypath/myscript2.js" ),
    $.getScript( "/mypath/myscript3.js" )
).done(function(){

    //place your code here, the scripts are all loaded

});
于 2013-03-06T14:11:44.397 回答
1

这是一个很好的解释为什么:

的语法$.when()$.when(one, or, more, deferreds)- 所以如果你想传递数组中的多个延迟,你需要 .apply() 因为你不想将方法调用构建为字符串并使用(在这种情况下eval这确实是邪恶的) .

jQuery 中的 $.when.apply(null, a method) 是什么意思?

于 2013-03-06T14:19:25.800 回答
0

好的,我使用以下解决方法让它工作。--> 也许任何人都可以解释一下区别,好吗?

$.when.apply($, (resultset.one, results.two)).then(...);

于 2013-03-06T14:12:45.807 回答