;

Minifying javascript files on the fly

Posted : Tuesday, 08 September 2009 08:21:31

Recently I've been writing an online mapping project using Bing maps for Enterprise and jQuery hosted within an ASP.NET web application. The script files contain a lot of lines of code script, a lot of comments and LOADS of white space - consequently they are getting fairly large in size! For a while now I've been meaning to write a custom handler for javascript files to minify them on the fly. Not only will this result in smaller files and therefore quicker download times but an added benefit is that it will be far harder for potential competitors to get unrestricted access to your helpfully commented, well structured and hard written code! I figured this would be a good subject for my first post!

So consider the following basic javascript example which takes a supplied array of tags and displays them randomly inside a containing div:

The aim of this post is to explain how to compress the javascript files that do this. As you can see if you view the source, the javascript contains a large number of both comments and whitespace.

The first step is to create the logic to actually minify the files. Although you could implement this yourself, there are many freely available algorythms that do this. In this case I used Douglas Crockfords JavaScript Minifier which is available in a variety of languages. The c# implementation contains a method called Minify( string src, string dst ) where src is the source filepath string and dst the destination filepath, as you might guess the contents of source file are minified and then written to destination file.

As this wasn't quite what I wanted (eg I want to output the minified string to the browser rather than a file) I altered the minifying code a little. First I altered the stream types used by the minifying code from StreamReader and StreamWriter to TextReader and TextWriter respectively.

    1 namespace JavascriptMinifier

    2 {

    3     class JSMinifier

    4     {

    5         const int EOF = -1;

    6 

    7         StreamReader sr;

    8         StreamWriter sw;

becomes

    1 namespace JavascriptMinifier

    2 {

    3     class JSMinifier

    4     {

    5         const int EOF = -1;

    6 

    7         TextReader sr;

    8         TextWriter sw;

Doing this enabled me to use other implementations of TextReader/TextWriter, specifically StringWriter, without having to change the actual minifiying logic. I then added an overload of the minify method to take a stringbuilder as the second parameter.

   60         public void Minify(string src, StringBuilder dst)

   61         {

   62             using (sr = new Post a comment Sharespacer Download source

  • (This will not appear on the site)