How to add onload JavaScript event in SharePoint?
SharePoint provides a JavaScript array "_ spbodyonloadfunctionnames", any function to be executed onload needs to be added to this array e.g.
_ Spbodyonloadfunctionnames. Push ("executemyfunctiononload ");
Now, why does your JavaScript function doesn' t execute if you just register it
With clientscript. registerstartupscript?
Actually, content pages can't execute JavaScript function on body load, reason; content pages can't directly add a function to the body's onload event if master page contains the <body> element (which is mostly true ).
This array is basically a part of init. JS located in "c: \ Program Files \ common files \ microsoft shared \ Web Server Extensions \ 12 \ template \ layouts \ 1033 \". if you open the Javascript file, you will notice the page onload event is handled by function _ spbodyonloadwrapper,
Which further callprocessdefaultonload, and this function executes all the function names added in array "_ spbodyonloadfunctionnames ".
FunctionAddloadevent(Func ){
VaR oldonload = Window. onload;
If (typeof window. onload! = 'Function '){
Window. onload = func;
} Else {
Window. onload = function (){
Oldonload ();
Func ();
}}}
Addloadevent(Nameofsomefunctiontorunonpageload );
Addloadevent(Function (){
/* More code to run on page load */
}
);