a/19723209/1636522

by wared

HTML

<div>Wait until initialization completes</div>

CSS

*{font-family:Consolas}
div{border-bottom:1px solid #cccccc;padding-bottom:4px;margin-bottom:4px;}

JavaScript

// Here is a way to deal with DOM ready event and Ajax calls at the same time :

var init, domready, ajax1, ajax2, ajax3;
ajax1 = $.ajax(prepare({ url: '/echo/json/', data: 'data 1' }));
ajax2 = $.ajax(prepare({ url: '/echo/json/', data: 'data 2' }));
ajax3 = $.ajax(prepare({ url: '/echo/json/', data: 'data 3' }));
domready = $.Deferred();
$(domready.resolve);

domready.always(function () { output('DOM ready'); });
ajax1.always(function () { output('Ajax 1 completed'); });
ajax2.always(function () { output('Ajax 2 completed'); });
ajax3.always(function () { output('Ajax 3 completed'); });
init = $.when(domready, ajax1, ajax2, ajax3);

// Then you don't need to care about the code above any longer :

init.done(function () { output('Initialization successful'); });
init.fail(function () { output('Initialization failed'); });
init.done(function ($, response1, response2, response3) {
    output('response3[0] : ' + JSON.stringify(response3[0])); 
    // Although the initialization has already been completed,
    // newly added callbacks still fire
    init.done(function ($, response1, response2, response3) {
        output('response1[0] : ' + JSON.stringify(response1[0]));
    });
});

// These functions below only serve as helpers. Read http://doc.jsfiddle.net/use/echo.html for details about the second one.

function output(str) {
    document.body.innerHTML += '<div>' + str + '</div>';
}

function prepare(settings) {
    return $.extend(settings, {
        type: 'POST',
        data: { 
            delay: Math.round(Math.random() * 3) + 1, 
            json: JSON.stringify(settings.data) 
        }
    });
}