7/21/2011

Some notes when write javascript

Avoid Using Eval() Function and With Statement

The eval() function executes a piece of code supplied as a string. For example, consider the eval() function call below:
eval("var myVar=100;alert(myVar);");
There is no way for the minifier tool to convert this string literal into a compact form. As a result the call will not be compacted. Similarly, using with statement also hampers the minification process.
var myVar = 100;
with(window) {
    alert(myVar);
} 
Since the minifier tool won't know whether myVar refers to the variable or to a member of window object the entire block will not be minified.

Try to Avoid Global Variables and Functions

Global variables and functions are never minified because there is a chance that they are used from some other part of the website. Consider the set of global variables and function below:
function MainFunction() {
    HelperFunction1();
    HelperFunction2();
}

function HelperFunction1() {
    alert("inside helper function 1");
}

function HelperFunction2() {
    alert("inside helper function 2");
}
Here, the functions HelperFunction1() and HelperFunction2() are used only by MainFunction() and are not used anywhere else. However, since they are in global scope, the minifier tool will not compact them. You can overcome this problem by modifying the code like this:
function MainFunction() {
    var HelperFunction1=function(){
        alert("inside helper function 1");
    }

    var HelperFunction2=function() {
        alert("inside helper function 2");
    }
    HelperFunction1();
    HelperFunction2();
}
Now, the minifier tool will compact both of the helper functions to smaller names and calls to them will also be substituted accordingly.

Use Shortcuts for Window and Document Objects

It is very common to use window and document JavaScript objects in the code. If you refer them as "window" and "document" at each and every place then you will be wasting bytes every time. Instead you can use them as shown below:
var w = window;
var d = document;
function MainFunction() {
    d.getElementById("Div1");
    w.setInterval(myCode, 1000);
}
You can even wrap frequently used methods of document object (such as getElementById) in a separate function like this:
function Get(id)
{
    return d.getElementById(id);
}
Then use the Get() function at all the places where you would have used getElementById() method.
function DoTest() {
 alert(Get("abc").id);
}

No comments:

Post a Comment