Javascript: Self-Executing Anonymous Functions

When writing functions in Javascript that you only need to run as soon as it’s created and not have to reference again, you can create a self-executing anonymous function using the syntax:
[cc lang=”javascript”](function(){
// your code goes here
})();[/cc]

In jQuery, you can have your anonymous function called after the document is ready as in
[cc lang=”javascript”]
$(document).ready(function() {
(function(){
//your code for the module
})();
});[/cc]

If you’re not using jQuery and want your anonymous function to be called after the page loads (as opposed to immediately before the page finishes loading), you can do

[cc lang=”javascript”](function(){
// your code goes here

// add event listener to trigger function call on page load
if (window.attachEvent) {
window.attachEvent(‘onload’, addHiddenFields);
} else {
window.addEventListener(“load”, addHiddenFields, false);
}
})();[/cc]

Another benefit is it doesn’t pollute the global namespace by not overriding other functions. To learn more, visit http://briancrescimanno.com/2009/09/24/how-self-executing-anonymous-functions-work/  and http://stackoverflow.com/questions/8248974/executing-jquery-functions-on-dom-ready-from-inside-a-module