There are many tools available on the net to compress javascript code but some powerful optimization techniques can enhance this compression to unprecedented levels. Today we are going to explore one of the most effective technique to achieve this compression.

Commonly in javascript code we refer to the document object or window object like

var element = document.getElementById(‘someElement’);

now imagine if we are using this type of line 20 times in the code then obviously it will keep increasing the size of the code .. until we can do something magical and reduce the size of the above line.

WOW!!! is it possible ???

Well the answer is yes, as everything in Javascript is an object and we have 2 ways of accessing the elements.

  1. Using the dot as shown in the code above

  2. Using the square brackets like

var element = document[‘getElementById’](‘someElement’);

Voila !! we are use this property to reduce the size of our javascript code


var $d = document, $gid = ‘getElementById’;

var e = $d[$gid](‘someElement’);

Now you can refer to document as variable $d and getElementById as $gid, so in whole source code document will be referred as $d i.e. 8 bytes to 2 bytes and for getElementById 14 bytes to 4 bytes or even less

Okay ! so now you have understood the concept but the question is how to maintain the readability of the code

the simplest technique to do so is name the variables like this

var $document = document, $getElementById = ‘getElementById’;

Therefore in the code you will see something like this:


This will preserve the readability of the code and when you are done with the project in the final phase when compression is to be achieved you can simply use some text editor to replace the $document with $d and $getElementById with $gid  and then run online tools like Closure Compiler or JSMinify or YUI

If you are an experienced programmer you can make use of the Regular Expression to replace the text automatically. I think PHP can be a good language to code such a thing….

Compressing Javascript To The Maximum Level (More than any tool can do)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.