SharePoint 2013 add javascript after whole page load

Kamil Biela picture Kamil Biela · Jun 5, 2013 · Viewed 97k times · Source

Disclaimer: I have no experience with SharePoint2013.

I have problem - I must include/fire some javascript functions after the whole page has been loaded. I tried listening to DOMDocumentReady and window.load events, but sharepoint render the rest of page after those events.

My question is: what I should do to be able to run script after whole page with ajax is rendered. Also I noticed that page navigation is based on hash (#) part. Obviously I must detect that moment also.

Any help or even link to right page in documentation would be great!

Answer

Will Fawcett picture Will Fawcett · Jun 26, 2013

You are right, MANY things happen on page after $(document).ready(). 2013 does provide a few options.

1) Script on Demand: (load a js file then execute my code.)

function stuffThatRequiresSP_JS(){
    //your code
}

SP.SOD.executeFunc("sp.js")

2) Delay until loaded (wait for a js file, then run)

function stuffToRunAfterSP_JS(){
    //your code
}
ExecuteOrDelayUntilScriptLoaded(stuffToRunAfterSP_JS, "sp.js")

3) load after other stuff finishes

function runAfterEverythingElse(){
    // your code
}
_spBodyOnLoadFunctionNames.push("runAfterEverythingElse");

Sources:

executeFunc: http://msdn.microsoft.com/en-us/library/ff409592(v=office.14).aspx

ExecuteOrDelayUntilScriptLoaded: http://msdn.microsoft.com/en-us/library/ff411788(v=office.14).aspx

Cant find a source on _spBodyOnLoadFunctionNames but I am using it in a few places.

good luck.