Maximize minification gains using Namespaces
masterTo get the smallest possible file size, avoid defining functions and variables in the global scope. Global names are never renamed by the minifier.
Best Practice: The Namespace Pattern Instead of global functions, define a single global object to act as a namespace. Define your public API as methods/properties on this object, and keep all other logic as local functions or variables within that object's scope. Local items will be renamed to short identifiers (e.g., single characters), significantly reducing file size.
Implementation Example:
var MyScope = new function()
{
var my = this;
var requestObject = null;
my.Status = 0;
my.Start = function(url)
{
if (my.Status == 0) { startRequest(url); }
else { alert("request processing"); }
};
// ... other methods ...
function startRequest(url) { /* local helper */ }
function cancelRequest() { /* local helper */ }
};In this pattern, MyScope.Start and MyScope.Status remain unchanged for external access, but requestObject, startRequest, and cancelRequest are all eligible for aggressive renaming.
var MyScope = new function()
{
var my = this;
var requestObject = null;
my.Status = 0;
my.Start = function(url)
{
if (my.Status == 0)
{
startRequest(url);
}
else
{
alert("request processing");
}
}
my.Stop = function()
{
if (my.Status != 0)
{
cancelRequest();
}
}
function startRequest(url)
{
// kick off the request
my.Status = 1;
}
function cancelRequest()
{
// cancel a pending request
my.Status = 0;
}
};