여기 여러 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