Attach JavaScript Functions to the onload event of body on SharePoint pages

As you all know that SharePoint is tricky to do things in comparison with Plain ASP.NET. Even though it's not easy but if you study it instead of implement what you want yourself, you can use functions which SharePoint provides and one of them is "spBodyOnLoadFunctionNames array" which is SharePoint provides a way to add your events to onload. Here's a usage below.

[code:js;ln=on]

// Usage
_spBodyOnLoadFunctionNames.push(”YourFunctionToAdd“);

[/code]

If you didn't know about it or if you want that onload event but you need to implement then use this below.
From JavaScript: The Definition Guide, Flanagan, O’Reilly

[code:js;ln=on]

/*
 * runOnLoad: portable registration for onload event handlers.
 * this source from JavaScript, The Definition Guide,  Flanagan, O'Reilly
 */
function runOnLoad(f) {
    if (runOnLoad.loaded) f();    // If already loaded, just invoke f() now.
    else runOnLoad.funcs.push(f); // Otherwise, store it for later
}
 
runOnLoad.funcs = [YourFunctionToAdd]; // The array of functions to call when the document loads
runOnLoad.loaded = false; // The functions have not been run yet.
 
// Run all registered functions in the order in which they were registered.
// It is safe to call runOnLoad.run() more than once: invocations after the
// first do nothing. It is safe for an initialization function to call
// runOnLoad() to register another function.
runOnLoad.run = function() {
    if (runOnLoad.loaded) return;  // If we've already run, do nothing
 
    for(var i = 0; i < runOnLoad.funcs.length; i++) {
        try { runOnLoad.funcs[i](); }
        catch(e) { /* An exception in one function shouldn't stop the rest */ }
    }
 
    runOnLoad.loaded = true; // Remember that we've already run once.
    delete runOnLoad.funcs;  // But don't remember the functions themselves.
    delete runOnLoad.run;    // And forget about this function too!
};
 
// Register runOnLoad.run() as the onload event handler for the window
if (window.addEventListener)
    window.addEventListener("load", runOnLoad.run, false);
else if (window.attachEvent) window.attachEvent("onload", runOnLoad.run);
else window.onload = runOnLoad.run;

[/code]

but the above one is much simple and easy to use in SharePoint. You can use this for regular HTML or .NET pages.