fbpx

Company News

JavaScript that Waits for the SharePoint API’s to be Ready

February 26, 2016

I’ve run into this countless times in SharePoint where I need the browser DOM to be ready, but also at the same time, SharePoint isn’t yet ready to perform operations against its APIs. The problem with using something like jQuery’s ready method is that will only get you a browser DOM that is ready, but the SharePoint pieces on the page haven’t necessarily yet rendered sufficiently, and the SP JavaScript API’s aren’t yet ready to respond to your method calls.

Below is a simple piece of pure JavaScript code (that’s right, no need for jQuery if that’s a limitation for you) that you can use to ensure that both the DOM is ready and the SharePoint page/API’s are ready.

This should work for on premise SharePoint. It may not work quite the same in Office 365. I may write another blog post to address that.

var mmmanTimeoutValue = 50; //In Milliseconds

function mmmanStartThisPage()

{

    mmmanWaitForPageReady();

    mmmanWaitForSPPageReady();

}

function mmmanWaitForPageReady()

{

    if (document)

    {

        mmmanPageIsReady();

    }

    else

    {

        setTimeout(mmmanWaitForPageReady, mmmanTimeoutValue);

    }

}

function mmmanWaitForSPPageReady()

{

    if (SP && SP != null && typeof SP == “object” && SP.ClientContext && SP.ClientContext != null && typeof SP.ClientContext == “function” && SP.ClientContext.get_current && SP.ClientContext.get_current != null & typeof SP.ClientContext.get_current == “function”)

    {

        mmmanSPPageIsReady();

    }

    else

    {

        setTimeout(mmmanWaitForSPPageReady, mmmanTimeoutValue);

    }

}

function mmmanPageIsReady()

{

    alert(“DOM Ready!”)

}

function mmmanSPPageIsReady()

{

    alert(“SP Ready!”);

}

Obviously where you see the alerts above, you simply replace that with your code that you need to run once SharePoint (or the DOM) is ready.

I’ve used this piles of times, and it’s worked great for me. Hopefully this is something you find value in as well.

Leave a Reply

Colin Phillips

itgroove Alumni

Colin Phillips

Subscribe via Email

Categories

Powered by...

itgroove Corporate Profile
Connect With Us