SharePoint Tip #19: Using JavaScript in Body OnLoad Event

When developing web parts or other controls that use JavaScript, it's quite common to need to call some function on the Body OnLoad event of the web page. The problem with this is that, in SharePoint, the Body element is in the master page and not in the control, so doing this is can be tricky.

Fortunately, the SharePoint team gave the developers a way to do this easily, using a special array called _spBodyOnLoadFunctionNames. The only thing you have to do is push your function's name to this array and it will get called in the OnLoad event of the window.

Example:

_spBodyOnLoadFunctionNames.push("MyFunction");

function MyFunction() {
    setTimeout('MyFunction()', 1000);
}