How to wait for all jquery loads to finish

77
November 23, 2018, at 4:50 PM

Using Jquery I'm replacing divs that have id's that start with 'lib_' with html from another file. It all works well, but I need to wait until they are all done before moving on in the code. The number of divs with 'lib_' could be none, or many. What I have here isn't waiting, it launches LoadStepPart5 before the .load is finished.

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);
    });
Answer 1

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

{

// code here

});

Answer 2

$.load follows standard jquery chaining, in that it returns the calling selector's jquery object. eg $("#id").load("url", callback).show(); will immediately show #id.

You are expecting a method that returns a promise: $.ajax

You can confirm this quickly in the browser console:

$("#a").load("url")
n.fn.init {context: document, selector: "#a"}
$.ajax({ url: "url" })
{readyState: 1, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}

Update your code to:

deferreds.push(
    $('#'+divID).ajax({
      { 
        url: "lib/library.html"
      })
      .done(function(html) {
        $("#"+divID).html($("<div>").html(html).find("#"+divID).html());
         console.log("this as html is loaded");
      })
 );
READ ALSO
How to manipulate contents of text file using FileReader in Javascript?

How to manipulate contents of text file using FileReader in Javascript?

I’m trying to create a table based on a text fileBecause of this I used JS FileReader

84
Laravel Valet Setup (Nginx) with CMS (Perch Runway)

Laravel Valet Setup (Nginx) with CMS (Perch Runway)

I'm attempting to set up Perch Runway on ValetLooking at the documentation Perch Runway CAN run on Nginx setup which Valet uses

65
How to retrieve checkbox value from table structured data?

How to retrieve checkbox value from table structured data?

I have a table which is having checkbox for each column as shown below:

65
Laravel session destroyed on page refresh

Laravel session destroyed on page refresh

I have an admin panel that I protect with user authenticationOnce I try to access it, it redirects me to the login form, which uses the 'guest' middleware (this is the expected behaviour)

76