Most browsers these days (with the exception of Safari, I think?) will accept gzip encoded content. This means you can drastically reduce the size of all those bloated javascript libraries you might be using on your web site.
So how do you serve gzipped js files?
There a few methods out there. I chose the one below since it was fast, easy and I’m hella freakin’ lazy.
The first step is to gzip all of the javascript files that you might be serving up. The fastest way I found was to just telnet into the server, and execute the following bash command:
gzip -cr <javascript directory>
Of course you’ll need to replace <javascript directory> with the correct directory that your javascript files are located in. The -c option tells gzip to keep the originals. This is important so that you can still serve non gzipped versions to browsers that don’t handle gzip! The -r option tells it to recurse through the directory. Now you should have a directory full of javascript files and their gzipped counterparts.
init.js
init.js.gz
jquery-ui.js
jquery-ui.js.gz
jquery.easing.js
jquery.easing.js.gz
jquery.history.js
jquery.history.js.gz
jquery.js
jquery.js.gz
swfobject.js
swfobject.js.gz
Yay. How exiciting, no?
The next step is to modify .htaccess to do some URL rewriting.
AddEncoding gzip .gz
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{HTTP_USER_AGENT} !Safari
RewriteCond %{REQUEST_FILENAME}.gz -f
RewriteRule ^(.*)$ $1.gz [QSA,L]
Essentially your telling the web server to server up gzip files, if the browser accepts them and the user is not on Safari and if there is a compressed version of the file available.
That’s really about it.
Here’s the difference in file sizes:
File | Size | Size (gZip) |
---|---|---|
init.js | 7628 | 1992 |
jquery-ui.js | 127787 | 50756 |
jquery.easing.js | 8097 | 2003 |
jquery.history.js | 5079 | 1771 |
jquery.js | 31033 | 15666 |
swfobject.js | 6722 | 2233 |
Pretty significant size difference!