Compressing CSS on the Fly

Published @Wed, 28th Oct 2009
When writing CSS files, people tend to like adding comments, indentation and extra whitespace to make the file easily readable and understandable. If you serve CSS in this manner to a web browser, you’re not being very efficient in your network use as all of the extra data (eg comments) is going to be ignored by the browser.

You can use applications like the YUI Compressor to maintain a stripped down version of your CSS in a separate file which is served to browsers, but that requires you to run the compressor after each modification you make, which is tedious. If you generate your CSS dynamically on the fly from a template file for example, you have further difficulties.

I wrote a mod_perl based output filter which compresses CSS on the fly using CSS::Minifier::XS. I have it running on this very website at the moment. You can see how it compresses a CSS file here:

wrapper.css

If you add “uncompressed” to the arguments then it will show you the response as it appears on disk, without it being compressed on the fly:

wrapper.css?uncompressed

At time of writing, the difference in size between the two responses is 28029 bytes vs 37645 bytes. You might say that 9.4KB isn’t a lot in these days of broadband access, but every little helps. On a dialup connection that single CSS file compression would knock two seconds off the page load time.

You can take a look at the module I wrote, and the Apache configuration by looking here CSSOutputFilter.pm

UPDATE:

The examples above don't actually work at the moment because I have removed mod_perl from my server to free up memory. You can still download the source code and use it yourself though.


If you want to read more stuff like this, follow my blog rss twitter or check out the rest of my articles: All, Perl related, Web related. If you found this article helpful, interesting or entertaining, and wish to donate:If you need a freelancer or some consulting, you'll find me at Cardwell IT Ltd.

CommentsAdding comments disabled for this post