Javascript compression filter

Yesterday a colleague asked me whether it is possible to automate compression of javascript code in a web application (the current project has a total of about 150kb of javascript for some of the pages). I decided to look into the issue a bit…

There are tons of offline javascript compressors/obfuscators etc. but the ones using Rhino seem to be among the best. This is mostly due to the fact that Rhino can fully interpret the code and decide whether, for instance, variables are local or not. Another good feature of Rhino is the fact that it is java based. The Dojo toolkit offers a patched version of the Rhino library which can be used safely to compres javascript offline.

I couldn’t find inline (filter based) compressors… so I decided to wrap the Dojo Rhino version in a filter. Took some work to figure out how Rhino is used, but I managed to get everything to work.

Instead of pasting code here I decided to install a subversion repository, it is browseable through the web from the following URL:

http://svn.maas-frensch.com/pmutils/javascript_compressor_filter/trunk/

The project contains a minimal webapp demonstrating the use of the filter, a simple build file (be sure to configure your tomcat base-dir for compiling) and can be checked out anonymously.

If you just want to use the filter download the following files and put them in your WEB-INF/lib folder (compiled for java5!):

This entry was posted in ajax, java. Bookmark the permalink.

2 Responses to Javascript compression filter

  1. erikvanoosten says:

    Interesting.
    You’re suggesting that comments are removed from the compressed output? Could you add that to the example?

  2. peter says:

    I replaced the example, this one should be a bit clearer. As you can see, all comments are stripped and local variables are renamed…. next to the more obvious removal of whitespace.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>