Minify Javascript and CSS with YUI Compressor

Posted in HTML and CSS and Javascript -

I've previously posted about minifying Javascript using a PHP port of Douglas Crockford's JSMin Javascript minifier but learned today of the YUI Compressor which does an even better job of minifying by replacing local symbols with 1 letter symbol names and other optimizations. It is also able to compress CSS files.

Requirements

The YUI Compressor needs Java to work and runs from the command line. The minimum version of Java required is 1.4. To install a Java runtime on Debian, for example, use the following command to find what runtimes are available:

aptitude search "?provides(java-runtime)"

and then e.g. to install openjdk-6-jre:

sudo apt-get install openjdk-6-jre

The YUI Compressor itself can be downloaded from the YUI Compressor page and clicking the "Download" link.

Using the YUI Compressor

It's simple to use, as shown in the following example. Replace /path/to with the actual path to the YUI Compressor, yuicompressor-2.4.2.jar with the actual version you are using, common.js with your input filename and common.min.js with the name you want the output file to be:

java -jar /path/to/yuicompressor-2.4.2.jar common.js -o common.min.js

And for CSS:

java -jar /path/to/yuicompressor-2.4.2.jar main.css -o main.min.css

Combine Javascript/CSS files first

To cut down on HTTP requests it's also a good idea to combine all your various CSS and JS files into a single file, and then compress them. On a Linux box it's as simple as using the "cat" command to concatenate them together into one file.

For example, in the directory where the Javascript files are:

if [ -e combined.js ]; then rm combined.js; fi
cat *.js > combined.js
java -jar /path/to/yuicompressor-2.4.2.jar combined.js -o combined.js

 and in the directory where the CSS files are:

if [ -e combined.css ]; then rm combined.css; fi
cat *.css > combined.css
java -jar /path/to/yuicompressor-2.4.2.jar combined.css -o combined.css

The if [ -e ... ] line tests to see if the combined file already exists and if it does it is deleted. This prevents it being included in the cat command. The *.js or *.css files are then concatenated into a single file which is then compressed with the YUI Compressor.

Note the input filename and output filename are the same for these commands; this is to avoid additional files being left over afterwards that need to be deleted.

The Results

On one of my sites, the combined Javascript files when not minified weighs in at 42,338 bytes. Using the PHP port of Douglas Crockford's JSMin drops this to 25,118 bytes. Using the YUI Compressor instead drops it to 22,716 bytes. When compressed it's 6,989 for JSMin and 6,507 for YUI. So there's not a huge saving in size between the two but every byte counts.

Further Reading

Read the YUI Compressor page for more details, and additional command line flags etc.



Related posts:


Comments