Monday, February 19, 2007

Compressed JS and mod_rewrite

Thanks to Joseph Scott's Compressed Javascript article and comments, I've managed to make some headway on making a solution that degrades nicely for browsers that don't support gzipped JS well at this point. Basically, by sticking to

<script type="text/javascript" src="js/prototype.js"></script>

and then letting apache serve up the gzipped file works best for me so far. By adding the following to my .htaccess file in my js directory

<FilesMatch "\\.js.gz$">
ForceType text/javascript
Header set Content-Encoding: gzip
</FilesMatch>
<FilesMatch "\\.js$">
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} !".*Safari.*"
RewriteCond %{HTTP:Accept-Encoding} gzip
RewriteCond %{REQUEST_FILENAME}.gz -f
RewriteRule (.*)\.js$ $1\.js.gz [L]
ForceType text/javascript
</FilesMatch>

I am able to push the correct headers to the browser as well as determine whether to serve up the js or js.gz version.

This also relies on the fact that a static precompressed gzipped version of the js file is created so there is little overhead required to gzip the file on every request. If the gzipped version of the file doesn't exist, it simply serves up the uncompressed file.

Of course there are a couple of caveats to this as if you change the JS file, you should update the gz file too or you will wonder why your changes aren't showing up.

Have fun!

New stomping grounds

I've decided to start a new blog for my misadventures and ideas. Hopefully something here will inspire you, if not leave you in awestruck. A few warning for those of you who may read this.

I'm not the most politically correct person.
I will offend SOMEBODY at SOME POINT.
I suck with grammar, so don't expect half of my posts to make sense. That's why this is a rambling.

Okay, back to work. Until then...