Using jQuery load with promises

Mike Fielden picture Mike Fielden · Jun 28, 2011 · Viewed 16.7k times · Source

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?

Answer

RredCat picture RredCat · Sep 6, 2013

I use next code for this case:

$.when(
    $.get('templates/navbar.tmpl.html', function(data) {
        $('#navbar').html(data);
    }),
    $.get('templates/footer.tmpl.html', function(data) {
        $('#footer').html(data);
    }),
    $.Deferred(function(deferred) {
        $(deferred.resolve);
    })
).done(function() {
    $.getScript("js/tools/jquery.min.js");
});

To my mind it looks more structured and pretty nice than previous implementations.