Cover image for Serve pre-compressed gzip JavaScript to browsers
Tyler Chipman
Tyler Chipman

Posted on

Serve pre-compressed gzip JavaScript to browsers

You can configure your server (via mod_deflate or others) to compress files on the fly, but for static content its a waste of CPU power.

Most browsers these days 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>
Enter fullscreen mode Exit fullscreen mode

Of course you’ll need to replace 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 recursively go through the directory. Now you should have a directory full of JavaScript files and their gzipped counterparts.

Enter fullscreen mode Exit fullscreen mode

Yay. How exciting, 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]
Enter fullscreen mode Exit fullscreen mode

Essentially your telling the web server to serve 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!

Top comments (0)