jqueryjquery-deferredjquery-loadpromise

Using jQuery load with promises


I'm still trying to wrap my head around deferred and what not, so with this in mind I have a question on how to do the following.

My team and I have 3 separate .load() methods that each go grab a specific template and append that to the same container. Each load takes a different amount of time as you might think, so when the content loads, it loads in a 'stair step' fashion (1, then 2, then 3). I'd like to make use of deferred objects and wait until they are all done, then append them at the same time to remove the 'stair step' action.

$('<div>').load(baseInfoTemplate, function () {
    var baseData = {
        // build some object
    };

    $.tmpl(this, baseData).appendTo($generalContainer);
});

All three calls are similar to the call above.

How can I achieve this?


Solution

  • $.load() isn't designed for use with Deferred objects, and also it is intended specifically to drop stuff into the page immediately.

    To solve that latter problem you either have to render the entire container outside the DOM, and then drop it in when they're all done, or you need to accumulate the three results and then put them all in in one go.

    The process below uses the latter approach:

    1. Use $.get() instead, and create an array of the jqXHR objects returned by $.get()

    2. Store the return fragments from each $.get() in an array too

    3. Use $.when.apply($, myArray).done(function() { ... }) to apply the templates and put them into the DOM

    See http://jsfiddle.net/alnitak/WW3ja/