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
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.

Guidelines:

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