SharePoint 2013 page onload event

Banner

You probably encountered a task to execute any of your scripts just after a SharePoint page loads. There are many articles and StackOverflow posts on this subject, but there is no obvious solution.

I gathered most popular solutions and compared them to find out the best and most useful one. They are:

jQuery function to run code on DOM load:

$(document).ready(MyFunction())

The most popular solution:

_spBodyOnLoadFunctionNames.push("MyFunction");

Internal function for delayed execution depending on other script presence:

SP.SOD.ExecuteOrDelayUntilScriptLoaded(MyFunction, "sp.core.js");

Internal function for delayed execution depending on events:

ExecuteOrDelayUntilBodyLoaded(MyFunction);

Load time

I tested these solutions execution time after page load on almost clean site.
As DOM load event occurred these functions ran in this order:
load times

Time is calculated relatively DOMContentLoaded event:

  1. 3 ms: ExecuteOrDelayUntilBodyLoaded(MyFunction);
  2. 4 ms: $(document).ready(MyFunction());
    ! At 12 ms the first paint occures and user can see the page.
  3. 25 ms: _spBodyOnLoadFunctionNames.push("MyFunction");
  4. 31 ms: ExecuteOrDelayUntilScriptLoaded(MyFunction, "sp.core.js");

Conclusion

As you can see, _spBodyOnLoadFunctionNames and ExecuteOrDelayUntilScriptLoaded run after internal SharePoint scripts are loaded, so they should be used if your script depends on them. Otherwise, it is better to use $(document).ready() or ExecuteOrDelayUntilBodyLoaded, so your code will execute before user can see any manipulations on the page.

Example of ExecuteOrDelayUntilBodyLoaded usage:

ExecuteOrDelayUntilBodyLoaded(SayHello);
function SayHello(){
    alert('Hellow World!');
}

Or just put your function inside ExecuteOrDelayUntilBodyLoaded if it is not going to be reusable:

ExecuteOrDelayUntilBodyLoaded(function(){
    alert('Hellow World!');
});

JQuery $(document).ready() function caused some problems in SharePoint 2010, but you can use it in SharePoint 2013, as well as internal functionality through ExecuteOrDelayUntilBodyLoaded.