CSS and Javascript Compression

Mar 11, 2008

Introduction

I've been using Javascript more and more ever since I discovered the wonderful jQuery framework. Though jQuery comes in a much smaller file size than Prototype, it's still quite a bit to ask of your dial-up users to download before the rest of your Javascript even loads. I also noticed a CSS file of mine was up to 8kB in size. I decided it was time to figure out a way to compress things down a bit. This is where my CSS and Javascript compression script comes in. Along with a little mod_rewrite magic, all the CSS/JS files on my client's website are automagically compressed and gzipped before sent to the site's visitors. File caching is included to reduce the processing time overhead from compression. A few options are also available for development to make life easier. It's hard to debug CSS when everything has been compacted into a single line, so adding &debug to the end of the path will revert back to the CSS file's original state so that you can browse through it (especially handy if you use the web developer toolbar). Using the compression script, my CSS file went from 8kB to 2kB, and jQuery from 95kB to 15kB!

Usage

Simply configure the constants at the beginning of the PHP file to suite your server appropriately. Now change the paths in your HTML to any CSS or Javascript file you'd like to compress (ie: from "/inc/style.css" to "c.php?f=inc/style.css").

Using mod_rewrite

You can use mod_rewrite to compress everything automatically: <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^(.*)\.(js|css)(.*)?$ inc/c.php?f=$1.$2$3
</IfModule>
Now going to "/inc/style.css" will automatically compact the CSS file and it will be Gzip compressed before being sent to your browser (provided your browser supports Gzip compression). Using this technique, you shouldn't have to change anything else on your site and everything will be compressed automatically.

Download

Added Mar 11, 2008
0 comments

More Posts

Other Places

Recent Photos

image image image image image image