Sharepoint - Using jQuery $(document).ready() in JavaScript Object Model

Document ready event gets fired when the DOM get loaded. This doesn't necessarily guarantee that the JS files required for SharePoint JSOM is already loaded.

The best way is

 SP.SOD.executeFunc('sp.js', 'SP.ClientContext', readyFunction);

function readyFunction() {
    Function1();
    Function2();
    Function3();
}

If I understand your question correctly, you are asking how to stack asynchronous calls so that the second function only executes when the first is complete.

Look into jQuery deferreds, they allow you to do exactly this: api jquery com

Take this as an example:

_spBodyOnLoadFunctionNames.push("Init");

function Init() {
    Func1().done(function() {
        Func2().done(function() {
            Func3().done(function() {
                // All three functions with asynchronous calls now completed in order successfully
            });
        });
    });
}

function Func1() {
    var dfd = $.Deferred();
    $.ajax({
        url: //url,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function (data) {
            // Do something with data if you want to
            dfd.resolve();
        },
        error: function (data) {
            // Do something with data if you want to
            dfd.reject();
        }
    });
    return dfd;
}

function Func2() {
    // Exactly as Func 1
}

function Func3() {
    // Exactly as Func1
}

First Func1 will execute. Only when the ajax call has returned successfully will Func2 then execute. If Func1's ajax call failed Func2 will not be executed. This is what the deferred object's resolve and reject functions ensure.

As you'll see in the link above, if you want Func2 to execute regardless of the result of Func1's ajax call then use the always method in place of done.

So the effect of the above code will be first Func1 begins and completes, then Func2 begins and completes, then Func3 begins and completes.

If you have a requirement to wait for the ajax calls from Func1 and Func2 to return successfully (in any order) before making the ajax call in Func3, you can do this:

function Init() {
    $.when(Func1(), Func2()).done(function() {
        Func3();
    });
}

If there is no dependency on one function running before another then your Init function just needs to look like this:

function Init() {
    Func1();
    Func2();
    Func3();
}

With this, although each function will be executed in order, the result of each one's asynchronous ajax calls could return in any order.

A note about _spBodyOnLoadFunctionNames. This is SharePoint's version of jQuery's $(document).ready. It ensures all SharePoint related elements are loaded.

Tags:

Jquery