SBB SBB - 5 months ago 19
Javascript Question

How can I know when Ajax calls are finished with getScript?

I am using jQuery

getScript
to load X amount of js files into my page. Each of those JS pages has an AJAX call in it that fetches data from the database.

I am using the
.done
method on
getScript
to see when all of the files have been loaded but I need to wait until all of the AJAX calls have been completed as well.

How can I go about waiting for the AJAX calls to finish in the included files via
getScript
before doing something?

$.getMultiScripts(moduleIncludes, 'includes/js/modules/').done(function() {
// All of the JS files have been included but we need to wait until those files have finished their AJAX call.
});

// Get array of JS scripts to load
$.getMultiScripts = function(arr, path) {

var _arr = $.map(arr, function(scr) {
return $.getScript((path || "") + scr);
});

_arr.push($.Deferred(function(deferred) {
$(deferred.resolve);
}));

return $.when.apply($, _arr);
}

Answer

You can use .ajaxStop()

Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event.

$(document).on("ajaxStop", function() {
  // do stuff when all `$.ajax()` call have complete
  $(document).off("ajaxStop")
});

$.getMultiScripts(moduleIncludes, 'includes/js/modules/').done(function() {
    // All of the JS files have been included but we need to wait until those files have finished their AJAX call.     
});