Minify your Javascript & CSS with YUI Compressor

Date: Sep 30 2010

Javascript / CSS minification simply means take a nice formatted Javascript or CSS file and take out all the white spaces comments and line breaks putting it all on one line to reduce file size and load time. Better load time equals happy visitors to your site. This article talks about implementation using the Yahoo YUI Compressor

Normal Javascript:

function headline_rotate() {
current_headline = (old_headline + 1) % headline_count;
$(“div.headline:eq(” + old_headline + “)”)
.animate({top: -205},”slow”, function() {

$(this).css(‘top’, ’210px’);
});
//Lots of comments here
$(“div.headline:eq(” + current_headline + “)”)
.animate({top: 5},”slow”);
old_headline = current_headline;
}

Minified Javascript:

function headline_rotate() {current_headline = (old_headline + 1) % headline_count;$(“div.headline:eq(” +old_headline + “)”).animate({top: -205},”slow”, function() {$(this).css(‘top’, ’210px’);});$(“div.headline:eq(” +current_headline + “)”).animate({top: 5},”slow”);old_headline = current_headline;}

I know it doesn’t seem like much but on large amounts of JS or CSS with commenting and formattingĀ  you can notice a decrease of up to 90% in file size. Typically 40-70% on average of your average formatted js or css file.

Javascript CSS minify : Otel ConsultingOn Otelconsulting.com we used a lot of the Web 2.0 technology for transitions, ajax look-ups and css tricks. The end result was a lot of javascript and css loading with every page. We needed to cut down on what we were delivering to the end user.

It’s very simple to do actually using yahoo YUI compression library. That’s a big word I know but this site makes it very easy to compress both css and javascript with the YUI compression library.

http://refresh-sf.com/yui/

Some things Otel Consulting recommends you consider is to keep a working formatted / commented copy of the JS and CSS files to make it easier to work with in the future.

Example
myjavascript.js = your formatted file
myjavascript-min.js = your minified version

Then just link your website to the myjavascript-min.js file. As you make updateds to the original myjavascript.js that is all cleanly formatted and commented use it to test then minify it as you make changes.

CSS Example on Otel Consulting Site:
Formatted Version
Minified Version

Taking it to the next level

For our site we have a custom scripts in place for our developers to just run a command and it updates all the pretty formatted to a nice compressed version. In some cases merging all our common javascript files into one minified file.

If you are on a linux based webserver which you probably are you can make use of the Yahoo YUI library directly via command line by following these instructions and then implementing your own script.

http://www.electrictoolbox.com/minify-javascript-css-yui-compressor/

Be Sociable, Share!

facebook comments:

Leave a Reply