Compressing JavaScript on the Fly

Written 14 years ago by Mike Cardwell

About a week ago I wrote a post about compressing/minifying CSS on the fly before sending it to the web browser. I used a mod_perl based OutputFilter in order to intercept outgoing text/css content and then compress it. Well, with the launch of Google Closure this week, I have done the same thing but for javascript. This time my mod_perl filter uses the compiler.jar provided by Google, so it requires Java to be installed.

The compiler is very intelligent. It will fully parse the javascript to make sure it is valid and will even rename variables and functions to shorter versions when it is safe to do so. It fully understands issues such as scope. Because it is so intelligent and because it uses Java, it can be a bit slow, so I added caching so it doesn’t have to repeatedly regenerate the compressed/minified version. You can take a look at it here: Compress/Minify JavaScript mod_perl Output Filter

Like with the CSS filter I made it so that adding “uncompressed” to the URI arguments shows you the original. Compare the following two urls:



At time of writing, the original uncompressed version is 8.3KB, whilst the compressed version is 4.5KB in size.


The examples above don’t actually work at the moment because I have removed mod_perl from my server to free up memory. You can still download the source code and use it yourself though.

Want to leave a tip?BitcoinMoneroZcashPaypalYou can follow this Blog using RSS. To read more, visit my blog index.