私は今日同じ問題に直面していて、約束とインターバルタイマーに基づいた解決策を思いつきました:
$.getScript("test.js", function() {
var $def = $.Deferred();
if (typeof foo === 'undefined') { // "foo" isn't available
var attempts = 0;
// create an interval
// that will check each 100ms if the "foo" function
// was loaded
var interval = setInterval(function() {
if (typeof foo !== 'undefined') { // loaded
window.clearInterval(interval);
$def.resolve();
}
// after X unsuccessfull attempts, abort the operation
else if (attempts >= 100) {
window.clearInterval(interval);
$def.reject('Something went wrong');
}
attempts++;
}, 100);
}
else { // "foo" is available
$def.resolve();
}
return $def.promise();
}).then(function() {
// at this point "foo()" is definitely available.
}).fail(function() {
// deal with the failure
});
foo
アイデアは、まだ存在しない変数(質問の例の関数)を公開する特定のスクリプトをロードすることです。そのため、スクリプトがロードされた後、getScript
この変数が存在するかどうかを確認し、そうでない場合は間隔を作成します変数が使用可能かどうかを継続的にチェックし、この条件が満たされた場合にのみ、promise を解決します。