Use Google's Closure Compiler in C#

Nov 8, 2009

A few days ago, Google released their Closure Compiler project for optimizing JavaScript. Here’s what they write about the Closure Compiler:

The Closure Compiler is a tool for making JavaScript download and run faster. It is a true compiler for JavaScript. Instead of compiling from a source language to machine code, it compiles from JavaScript to better JavaScript. It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what's left.

The interesting part of the Closure Compiler is that it not only removes whitespace, it also rewrites your JavaScript code to make it smaller and optimizes the code for better performance. My tests show that it can reduce JavaScript files by about 60% - and that’s before HTTP compression! Considering how much JavaScript a modern website uses, this is no less than amazing and highly useful.

The Closure Compiler comes in two flavors – a Java based command line tool and a RESTful API. I’ve been playing around with the API and it works great and very fast.

The code

The C# class I’ve written takes a JavaScript file and passes it through the API and then returns the compressed JavaScript as a string. The class contains one public and one private method and is only 47 lines of code including 16 lines of comments.

public string Compress(string file)

{

  string source = File.ReadAllText(file);

  XmlDocument xml = CallApi(source);

  return xml.SelectSingleNode("//compiledCode").InnerText;

}

 

private static XmlDocument CallApi(string source)

{

  using (WebClient client = new WebClient())

  {

    client.Headers.Add("content-type", "application/x-www-form-urlencoded");

    string data = string.Format(PostData, HttpUtility.UrlEncode(source));

    string result = client.UploadString(ApiEndpoint, data);

 

    XmlDocument doc = new XmlDocument();

    doc.LoadXml(result);

    return doc;

  }

}

How to use it

You can use the class to do various cool things. You can write a MSBuild or NAnt script that automatically compresses your JavaScript files as part of a continuous integration process or, as I prefer, write a HTTP handler to do the same but at runtime. Remember to output cache the compressed result. Here's an example of using the class from ASP.NET:

GoogleClosure gc = new GoogleClosure();

string script = gc.Compress(Server.MapPath("~/script.js"));

Remember that the class doesn't do any exception handling, so you might want to stick that in yourself.

Download

GoogleClosure.zip (905,00 bytes)

* $4.95/month ASP.NET Hosting with FREE SQL 2012 DB! – Click Here!

Comments (4) -

Chris Arkwright
Chris Arkwright United States
11/8/2009 6:58:52 AM #

Good stuff Mads. I recently read the article regarding the Closure Tools via the Google Code Blog, and it definitely looks interesting. I have not personally used it yet, but this article really exhibits the great potential of their new toolset. Great resource! Bookmarked.

Frederik Vig
Frederik Vig Norway
11/8/2009 8:31:03 AM #

Cool , didn't know they had a Service API as well. Here is the format of the returned xml, for reference: code.google.com/.../api-ref.html#out

Chris Owen
Chris Owen United Kingdom
11/10/2009 7:17:37 AM #

This is really cool, and actually I think Its worth pushing this forward a but more.

With http://www.dotlesscss.com we have a HttpHandler that will compile our Less files and hold them in HttpContext.Cache until the file changes (or cache is recycled). Something like this would be great, as you could just upload your unoptimized JS and let the handler sort it out.

francis
francis Canada
11/13/2009 6:22:50 PM #

Microsoft Ajax Minifier 1.1

"The Microsoft Ajax Minifier enables you to improve the performance of your Ajax applications by reducing the size of your JavaScript files. The Microsoft Ajax Minifier supports two levels of minification: normal crunching and hypercrunching. Normal crunching refers to the process of removing unnecessary whitespace, comments, semicolons, and curly braces. Hypercrunching refers to the process of shortening the names of local variables and removing unreachable code.

The Microsoft Ajax Minifier includes the following components:

    * Command-line tool -- Enables you to minify JavaScript files from a command prompt.
    * MSBuild Task -- Enables you to minify JavaScript files in a Visual Studio project automatically when performing a build.
    * Component -- Enables you to to use the Microsoft Ajax Minifier programmatically."

aspnet.codeplex.com/.../ProjectReleases.aspx

Pingbacks and trackbacks (13)+

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.