Home / AJAX

Other Coding Tips

RSS
Modified on 2009/12/14 23:51 by Stephen Walther Categorized as Uncategorized
Try to use object and array literals instead of the new operator and the Array and Object constructors. This will save nine or ten bytes per instance:

var o = new Object();               // long way
var o = {};                         // short way
var a = new Array();                // long way
var a = [];                         // short way
var a = new Array(one, two, three); // long way
var a = [one,two,three]             // short way

However, Microsoft Ajax Minifier will automatically make these substitutions unless the –NEW:KEEP parameter is specified.

The document and window objects are typically used over and over again within JavaScript code. It’s a good idea to shortcut those object within your namespace, thereby allowing minification to reduce the six or seven characters for each instance down to a single character:

var w = window;
var d = document;
// use w and d in your code instead of window and document

For DOM methods that are used frequently, supply local (and therefore renamable) shortcuts. For example, document.getElementById might be used many times in your code. Create a shortcut function:

function GetElById(id)
{
    document.getElementById(id);
}

That function name could be renamed to a single character, thereby distilling document.getElementById(“id”) down to E(“id”). That’s a savings of over twenty characters per instance (not counting the original shortcut function). For frequently-used functions, the savings add up quickly.