12

I've been using with great success the

$(document).ready(function() { 
    FunctionName();
});

in a SharePoint WebPart code snippet to fire off COSM CAML queries using JavaScript to build various html outputs from a SharePoint list. Works great. But now I need to run three functions when the page loads. So I used the used the following but only the first function runs. I can switch positions of the function names but the first one will run. Thought it would be a no brainer. Silly me. Thoughts?

$(document).ready(function() { 
    FunctionName1();
});
$(document).ready(function() { 
    FunctionName2();
});
$(document).ready(function() { 
    FunctionName3();
});
  • Thank you. It appears that I need to move away from the jQuery to the SharePoint standard – PianoMan Jun 4 '16 at 4:54
2

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.

  • Not my original intent, but I can see how this can be very useful. Current I using the functions to pull from a list to build a JumboTron, then pull from three separate lists to build a left, middle and right column. I'll try these ideas out and see how they work. Thanks – PianoMan May 27 '16 at 3:57
  • Garurravs, I looked this over and this appears will work find as it will allow the passing of parameters. Currently I'm not at the point of parameter passing but move very quickly to the light at the end of the tunnel. One of the leap out at me questions with SP.SOD.executeFunc('sp.js', 'SP.ClientContext', readyFunction); was how to pass parameters and you have the answer. Thanks – PianoMan Jun 9 '16 at 16:30
12

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();
}
  • You the man!! I was just runing them in a series: SP.SOD.executeFunc('sp.js', 'SP.ClientContext', Function1); SP.SOD.executeFunc('sp.js', 'SP.ClientContext', Function2); SP.SOD.executeFunc('sp.js', 'SP.ClientContext', Function3); But this method failed if code was in a different webpart column, ie, the body and a nav. Your method works so yes I agree it is a better way. – PianoMan Jun 24 '16 at 19:52
  • Spoke to soon. Only work if I "hard reload" ie F5(refresh) Opening the page from a link fails to run the code. I have the run code in a code snippet at bottom of page. Then body column of the page template has function1 which build content and in the Right column is a funtion that builds a quicklink list. They run sepearatly but not unison unless a hard load the page F5. Any ideas why and how to correct? – PianoMan Jun 24 '16 at 20:41
  • Are the JS code in different files? Before executing each function check if previous functions are executed with the help of a flag variables. If the variable is false then invoke functions from the beginning. – Amal Hashim Jun 24 '16 at 20:46
  • Thanks for the tip. I should of mentioned that it runs in Chrome without the need of a hard reload - page loads and both run. Not sure what is going on – PianoMan Jun 27 '16 at 19:59
0

You can have only one $(document).ready in your html but jquery provides another way to handle this for multiple function calls on page load. Use this:

$(function(){
function1();
function2();
function3();
}); 

Here

$(function(){
...
});

is equivalent to $(document).ready but the advantage is that you can call more than one function from within it or you can even declare it multiple times, once for each function call separately and all functions will be called as soon as the page loads as follows:

$(function(){
function1();
});

$(function(){
function2();
{);

Try it once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.