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!

1 comment:

Adam said...

I don't know if some escaping happened but in the FileMatch, there should only be one backslash.

Also, I had to remove the colon after the Content-Encoding to get mine to work.

Otherwise, thanks! This helped me a lot!