Javascript/CSS Minification With YUI Compressor

Posted on April 24, 2012


'Minification' is a process of compressing the source code, without changing it's functionality. This technique is useful sometimes, specially in the case of a web application with huge Javascript/CSS files. In other cases, it's probably just a micro-optimization. Minifying js/CSS files will reduce the bandwidth used and also improves the performance of the application. As per Wikipedia Source:
Minified source code is especially useful for interpreted languages deployed and transmitted on the Internet (such as JavaScript), because it reduces the amount of data that needs to be transferred. Minified source code may also be used as a kind of obfuscation. In Perl culture, aiming at extremely minified source code is the purpose of the Perl golf game.

Minified source code is also very useful for HTML code. As an example, successive whitespace characters in HTML are rendered as a single space, so replacing all whitespace sequences with single spaces can considerably reduce the size of a page.

There are a couple of tools available to minify js/CSS code, like Google's Closure-Compiler, Yahoo's YUI Compressor, JSMin, etc. If you are using Maven for your build process, you can use the Maven plugin for YUI Compressor, as below:



And the plugin repository, is as below:



I created a sample web application with "js" folder to store javascript files and used the above configuration to test the 'Minification' process. I downloaded the latest version of JQuery (both files - 'Minified' and 'Uncompressed' 1.7.2 version files) and copied it to my "js" folder and built the web application using Maven. The downloaded JQuery files weighed as noted below:
JQuery-1.7.2.js --> 253 KB
JQuery-1.7.2.min.js --> 95 KB

After the Maven Build, the JQuery-1.7.2.js is minified and the minified js file weighed as noted below:
JQuery-1.7.2-min.js --> 108 KB

The above results show that the 'Minification' process is working pretty fine. So, if you are using a lot of javascript/css files in your web application, consider minifying your js/css code, so that you can reduce the data transferred and also improve the performance of your web application. In some cases, it might be a micro-optimization. So, let me also remind you that 'Premature Optimization is the root of all evil'.

Blog Categories
Disclaimer
The views expressed on this blog are my personal views and do not reflect the views of my employer or campaigns I am supporting.

All sample code is provided for illustrative purposes only. These examples have not been thoroughly tested under all conditions. The writer therefore, cannot guarantee or imply reliability, serviceability, or function of these programs.

All programs contained herein are provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.