By: Omar Stewart
For those of you who are unfamiliar with JavaScript namespaces, they basically serve the same purpose as a namespace in other languages. In JavaScript, it can be a neat and clean way to wrap all your JavaScript functionality. This makes for an even cleaner implementation when you load your JavaScript from an external file. In this tutorial, I'll show you how to quickly set up your custom namespace and load it into your SharePoint MasterPage.
I'll begin by loading Randy Drisgill's Starter Masterpage, available on codeplex.

Now I'll create a document library where my script files will live. From SharePoint Designer, I'll just create a new document library and call it "Script Library"..

In my script library, I'll create a new javascript file and call it "myJavaScriptFile.js"

We'll create our namespace within a function just to make it easy for SharePoint to access.
//Create our wrapper function
function TheSharePointBlogScript() {
//Check if our namespace exists
if (!TheSharePointBlog)
//If not, Declare our namespace
TheSharePointBlog = {
//Define functions
grabAllLinks : function() { document.getElementsByTagName ("A"); }
grabAllTableRows : function() { document.getElementsByTagName("TR"); }
printError : function(err) { alert("err") }
};
}
}
I'll save my changes.
Now that I have my file, I can drop it into my masterpage. The good folks in Redmond have made It very simple to call a function after when our masterpage loads.
The _spBodyOnLoadFunctionNames array is an array of functions that gets loaded when a SharePoint page is loaded. All we need to do is add our wrapper function to that array.
Lets jump back to our starter master page, scroll down to the HEAD tag and add our external script file.
<script language="javascript" type="text/javascript" src="../ScriptLibrary/myJavaScriptFile.js"></script>
Now I can actually add our function to the Array..

<script type="text/javascript" >
_spBodyOnLoadFunctionNames("TheSharePointBlogScript");
</script>
Our function will now be created masterpage loads and we can access our namespace object throughout the document..
<script type="text/javascript">
Var rows = TheSharePointBlog .grabAllTableRows ()
</script>
This is a nice way to create manageable javascript in SharePoint.
By: Omar Stewart