如何等待所有jQuery加载完成

时间:2018-11-23 07:20:07

标签: jquery load jquery-deferred

使用JQuery,我要替换ID为以“ lib_”开头的div的div,并使用html替换另一个文件中的html。一切都很好,但是我需要等到它们全部完成后才能继续进行代码。带“ lib_”的div的数量可以为无或多个。我在这里没有等待,它在.load完成之前启动LoadStepPart5。

let deferreds = [];

    $('[id^="lib_"]').each(function(){
        let divID = $(this).attr('id');
        let libID = divID.replace('lib_','');

        deferreds.push( $( '#' + divID ).load( "lib/library.html #" + libID, function(){
            console.log("this appears later, code didn't wait");
        }));
    });

    $.when.apply(null, deferreds).done(function() {
        console.log("immediately displayed");
        LoadStepPart5(n,xml);
    });

2 个答案:

答案 0 :(得分:1)

$.load遵循标准的jquery链接,因为它返回调用选择器的jquery对象。例如$("#id").load("url", callback).show();将立即显示#id

您期望有一个返回promise的方法:$.ajax

您可以在浏览器控制台中快速确认这一点:

$("#a").load("url")
n.fn.init {context: document, selector: "#a"}

$.ajax({ url: "url" })
{readyState: 1, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}

将您的代码更新为:

deferreds.push(
    $.ajax(
      { 
        url: "lib/library.html"
      })
      .done(function(html) {
        $("#"+divID).html($("<div>").html(html).find("#"+libID).html());
         console.log("this as html is loaded");
      })
 );

答案 1 :(得分:0)

$(window).on('load',function()

{

//代码在这里

});