Monday, November 10, 2008

CSS and JS compression

A web project has lots CSS and JS files associated with it and lots of these files does affect the page load time based on the internet speed, its size etc.

It would be a wise option to compress the CSS and JS files to make download of these on the fly much faster.
1) GZIP compression
2) Remove unwanted space, line feed characters in JS.
3) Use smaller variable names
4) Remove comments

For (1) - Most of the application servers come with option of enabling compression for HTTP and HTTPS. For example in Tomcat you can do it by setting in the server.xml
...
<connector acceptcount="100" connectiontimeout="60000" disableuploadtimeout="true"
port="9014" redirectport="8944" scheme="https" proxyport="443" compression="on"
compressablemimetype="text/html,text/xml,text/plain,text/css,text/javascript">
...
Having 2, 3 and 4 done on the code base will make it ugly and not readable. There are lots of open source tool which can help as they does all these during build time when creating the achieves.

For example one such tool would be Yahoo UI compressor - it has a easy maven plugin as well - click here for more details on usage.