How to control the order of functions being called in jQuery $(document).ready

jquery

Solution

Asynchronous requests fire in order, but will return in whatever order they complete in first. So there is not a sure fire way to force them to end at the same time, however, you can build rules to only run code after certain groups have returned.

For instance, define a callback function with a set of rules, and pass it to each `success` callback for all of your ajax requests.

var completedObject = {};

function groupSuccessCallback() {
  // Test for any combination of requirements
  if ( completedObject.ajax1 && completedObject.ajax2 ) {
    ... // Do something that only requires 1 and 2
  }
  if ( completedObject.ajax1 && completedObject.ajax2 && completedObject.ajax3) { 
    ... // Do something that requires all 3 being done
        // your data is available at completedObject.ajax#
  }

  // Or test for _all_ entries for a dynamic count
  var allComplete = true;
  for(var i in completedObject) {
     if ( completedObject.hasOwnProperty(i) && !completedObject[i] ) {
       allComplete = false;
     }
  }

  // Do whatchya need.
  if (allComplete) { 
    alert("bb-b-bb-b-b-b-bbb... that's all folks!");
  }
}

Then set the flags inside of your success functions:

// Ajax1
completedObject['anything'] = false; // instantiate a dynamic entry in the object or use an array if you can't use names.
$.ajax({
  ...,
  ...,
  success: function(data) {
    completedObject['anything'] = data || true;
    groupSuccessCallback();
  }
});

Problem

I need to be able to control the order of items being processed in the `$(document).ready` event. These are multiple controls, loaded from multiple files, all asking to be called in the `ready` event. They all start an async call to the server (AJAX). Only after they are all done, I need to do some extra work. What would be the elegant solution for this?

Original source