Handle multiple ajax calls in a fixed incremental order

In a project which I’m working on, I’ve realized a Javascript object (I’ve called it MediaBrowser), which displays images and flv videos into a box (a dynamic div rendered at runtime). The data used by this object is contained into multiple XML files, which are loaded by ajax (potentially it can loads infinite files passed as array of urls). The problem was: ajax is by definition asynchronous, so each time I load the page with my cool MediaBrowser, the order in which the objects (images and videos) are processed and displayed varies based on the order in which responses to the ajax calls are returned. IE: if I call file_1.xml, file_2.xml and file_3.xml, which contain respectively:

  • file_A, file_B, file_C
  • file_D, file_E
  • file_F

I can get the following display order:

  1. file_A
  2. file_B
  3. file_C
  4. file_D
  5. file_E
  6. file_F

which is what I want, but more probably I will get a similar order:

  1. file_D
  2. file_E
  3. file_A
  4. file_B
  5. file_C
  6. file_F

because the ajax responses are returned (due to the case) in this order: file_2.xml, file_1.xml and file_3.xml. This is not acceptable, specially due to a project requirement which force the reload of the page each time the user select any of the object displayed in order to see its details.

So, I’ve realized a sort of “priority tail” by adding an extra XML node, called <priority> to the XML document returned from the ajax call. This has been possible by using the parameter dataFilter provided by jQuery’s $.ajax() method, which accepts a function callback to apply an extra data-processing operation.

This is a piece of code:

  type: "GET",
  url: XMLUrl,
  dataType: "xml",
  cache: this.cacheAjax,
  success: this._storeData,
  error: this._storeError,
  dataFilter: function(data) {

    var root, newNode, newNodeValue;

    root = data.getElementsByTagName('pics')[0];
    newNode = data.createElement("priority");
    newNodeValue = data.createTextNode(priority);

    return data;


The priority variable is passed as a parameter to a method (this._startAjaxRequest()) that wraps the jQuery code ($.ajax()). In this way I can store the data retrieved (basically i put the XML documents into an array) from the ajax calls randomly (based on the responses order) and then I can sort the store (by using the priority value) and display the objects always in the same order.

This is a piece of code of this._storeData() that shows how the data is stored for further processing operations:

this._storeData = function(xhr) {

  var XMLDoc = xhr.documentElement;

  // adds the XML document to the MediaBrowser's dataStore
	doc: XMLDoc,
	priority: XMLDoc.getElementsByTagName("priority")[0].firstChild.nodeValue

…and this is the method which sorts the data into array:

this._sortDataStore = function() {
    function(a, b) {
      return a.priority - b.priority;