ここで私はいくつかのJSファイルを順番に読み込もうとします。問題が$.when
の場合、チェーンが完了するまで待機しません。しかし、最後の$.Deferred.then
は期待どおりに動作します。 $.when
を動作させるにはどうすればよいですか?
var urls = [
"https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js",
"https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe.js",
"https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe-ui-default.js"
];
var xxx = $.Deferred();
xxx.then(function() {
options = {
dataType: "script",
url: urls[0],
cache: false
};
return $.ajax(options).promise();
})
.then(function() {
options = {
dataType: "script",
url: urls[1],
cache: false
};
return $.ajax(options).promise();
})
.then(function() {
options = {
dataType: "script",
url: urls[2],
cache: false
};
return $.ajax(options).promise();
}).then(function() {
$("body").append("This is correct. All files are loaded.<br>");
});
$.when(xxx).done(function() {
$("body").append("This is wrong. JS files are not loaded yet.<br>");
});
xxx.resolve();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
フィドル https://jsfiddle.net/ergec/fmrj6qgp/
あなたは '$の.when'を使用したい理由その後、予想通り、それは' $ .Deferred.then'で作業している場合は? –
'$ .when()'や '$ .Deferred()'を使う理由はありません。 '$ .ajax(...)、then()'でチェーンを開始します。最後の '.then()'ハンドラは、チェーン全体がいつ完了したかを知るのにうまくいくはずです。戻り値 '$ .ajax(...)'が正常に動作するときに 'return $ .ajax()。promise()'を使う理由もありません。 – jfriend00