7. Minify JavaScript

JavaScript, like most other languages, is a language that requires the developer to use a nice structure when writing it – a structure that requires the use of line breaks, indentation and comments. Otherwise it becomes difficult to maintain.

Minify JavaScript

The problem with line breaks, indentation (tabs or spaces) and comments are that they add to the weight of the file. Remember that line breaks, tabs and spaces are also characters even though not visible in the sense most other characters are. When browsers parse JavaScript they do not use those extra characters for anything – they also ignore all comments in the code.

  • First, for inline JavaScript and external files that you don't want cached, the smaller file size reduces the network latency incurred each time the page is downloaded.

  • Secondly, minification can further enhance compression of external JS files and of HTML files in which the JS code is inlined.

  • Thirdly, smaller files can be loaded and run more quickly by web browsers.

Guidelines:

  • Minify Javascripts to remove comments, remove white-spaces and line breaks.

  • Obfuscate Variables using the smallest variable name possible.

  • Minify any JS files that are 4096 bytes or larger in size.

  • You should see a benefit for any file that can be reduced by 25 bytes or more (less than this will not result in any appreciable performance gain).

Example:

Consider a JavaScript file with the following content:

// Does something with the selected ID function DoSomething(id) { if (id == 0) { alert('Id is invalid'); } }

When the browser will parse the file above, it actually only needs this next line to do exactly the same:

function DoSomething (id) { if(id==0) {alert('Id is invalid')} }

If we could provide the browser with the second file instead of the first, the download size would be 50% smaller. Depending on the amount of comments and whitespace in your JavaScript files, expect your mileage to vary. The important thing is that we need to write in the style of the first example for maintainability, but serve the second example to the browser for performance.

Tools:

Several tools are freely available to minify JavaScript, including the Closure Compiler, JSMin or the YUI Compressor