Use Google's Closure Compiler in C#

by Mads Kristensen 8. November 2009 15:26

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)

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Tags: , ,

ASP.NET | Client-side

Comments

11/8/2009 3:45:08 PM #

pingback

Pingback from topsy.com

Twitter Trackbacks for
        
        Use Google's Closure Compiler in C#
        [madskristensen.net]
        on Topsy.com

topsy.com |

11/8/2009 3:58:52 PM #

Chris Arkwright

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.

Chris Arkwright United States |

11/8/2009 4:54:10 PM #

trackback

Social comments and analytics for this post

This post was mentioned on Twitter by mkristensen: Just blogged: Use Google's Closure Compiler in C# http://tinyurl.com/yk5p3ge #javascript #optimization

uberVU - social comments |

11/8/2009 5:31:03 PM #

Frederik Vig

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

Frederik Vig Norway |

11/8/2009 8:32:32 PM #

trackback

Use Google's Closure Compiler in C#

You've been kicked (a good thing) - Trackback from DotNetKicks.com

DotNetKicks.com |

11/8/2009 9:47:35 PM #

trackback

Use Google's Closure Compiler in C#

Thank you for submitting this cool story - Trackback from PimpThisBlog.com

PimpThisBlog.com |

11/9/2009 10:28:23 AM #

pingback

Pingback from blog.adrweb.net

Zaragon blog » Google Closure Compiler in C#

blog.adrweb.net |

11/9/2009 11:27:22 PM #

pingback

Pingback from random.cgi-biz.com

ASP.NET - Google Closure Compiler C - Random Things To Blog

random.cgi-biz.com |

11/10/2009 9:36:11 AM #

pingback

Pingback from blog.cwa.me.uk

Reflective Perspective - Chris Alcock  » The Morning Brew #474

blog.cwa.me.uk |

11/10/2009 4:17:37 PM #

Chris Owen

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.

Chris Owen United Kingdom |

11/14/2009 3:22:50 AM #

francis

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

francis Canada |

11/16/2009 3:09:04 AM #

trackback

Interesting Finds: 2009 11.09 ~ 11.16

.NET BitTorrent in Silverlight WPF : A* search ExifLibrary for .NET More Data Binding Make your site

gOODiDEA.NET |

11/16/2009 3:09:31 AM #

trackback

Interesting Finds: 2009 11.09 ~ 11.16

.NETBitTorrentinSilverlightWPF:A*searchExifLibraryfor.NETMoreDataBinding...

gOODiDEA |

11/17/2009 1:18:35 PM #

pingback

Pingback from 44crosbyrow.com

Use Google's Closure Compiler in C#

44crosbyrow.com |

12/10/2009 1:49:58 AM #

pingback

Pingback from enginechris.wordpress.com

Squish, Squash and Mash your Javascript Files Together! « Chris J Owen

enginechris.wordpress.com |

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008