下面的代码有严重的语法错误。可能是因为我用了for之类的。
$.when(
for (var i=0; i < 5; i++) {
$.getScript( "'" + someArr[i].fileName + ".js'");
}
$.Deferred(function( deferred ) {
$( deferred.resolve );
})
).done(function() {
alert("done");
});
我正在尝试调用几个脚本,然后当它们全部加载时,我想要一个警报来显示。
带注释的(但未经测试的)解决方案如下
// When takes a promise (or list of promises), not a random string of javascript
$.when((function() {
// First we need to define a self resolving promise to chain to
var d = $.Deferred().resolve();
for ( var i = 0; i < 5; i++ ) {
// Trap the variable i as n by closing it in a function
(function(n) {
// Redefine the promise as chaining to itself
d = d.then(function() {
// You can *return* a promise inside a then to insert it into
// the chain. $.getScript (and all ajax methods) return promises
return $.getScript( someArr[n].fileName + '.js' );
});
// Pass in i (becomes n)
}(i));
}
return d;
// self execute our function, which will return d (a promise) to when
}())).then(function() {
// Note the use of then for this function. done is called even if the script errors.
console.log( 'done' );
});
如果你有这个选项,更简单的是
$.when(
$.getScript( 'fileName1.js' ),
$.getScript( 'fileName2.js' ),
$.getScript( 'fileName3.js' ),
$.getScript( 'fileName4.js' )
).then(function() {
alert("done");
});
如果我理解正确的话,您可以使用$.map()
和$.when.apply()
简洁地编写代码,如下所示:
// First scan someArr, calling $.getScript() and building
// an array of up to 5 jqXHR promises.
var promises = $.map(someArr, function(obj, index) {
return (index < 5) ? $.getScript(obj.fileName + ".js") : null;
});
// Now apply the promises to $.when()
$.when.apply(null, promises).done(function() {
alert("done");
});
注:$.when.apply(null, promises)
相当于:
$.when(jqXHR0, jqXHR1, jqXHR2, jqXHR3, jqXHR4);
其中jqXHR0
等为5次$.getScript()
调用返回的jqXHR
对象。