topbarExpand or Collapse

Recent Posts

Productivity Wallpaper
How Not to Design a Form
Time Wasters: Guitar Hero/Rock Band Clone and Physics Games
Prag Pub Issue 1 out
Full Frontal
Custom Yahoo Status WPWidget
Remove .svn directories
Yahoo! Purple Hack & Open Hack Day MNL
Google/Globe Developer Workshop and Thoughts
Coda

Categories

Tags

 

Development

CSS and JS compression through ASP.NET

Tags: , ,


24 Feb
2008
 

In this article, I will discuss a technique for distributing compressed website assets (CSS and javascript files) using ASP.NET. Compressing these files reduces bandwidth usage, which means decreased costs on server traffic. (Take 10,000 viewers/users and up, and the savings become significant.)

Compression of web content can be done in several ways. A typical solution is to gzip-compress content before sending it back to the browser. This can be enabled on IIS 6.0 easily. Another solution, would be to optimize files by removing unnecessary elements (whitespace, comments, altering variable names etc etc). Typically this is done through an external application that processes the files and gives you optimized files for use in your application. Both solutions can be combined for even more improvement. My solution is based on the idea of the latter technique, but allows it without the use of an external application.

This solution is accomplished through the use of ASP.NET’s HttpHandlers. The handler is designed to process .css and .js files. It reads the file, performs the necessary optimization, then sends a response back to the client. For more information on implementing your own HttpHandler check out Michael Flanakin’s post right here.

Code Listing (CompressedHandler.cs)

The handler reads in the file, reads it content to memory, then does the optimization. For css files, I’ve simply removed unnecessary white space and comments (lines 22-27). For js files, I’ve used the excellent JSCompressor class by Eric Woodruff.

It’s that simple. Of course, don’t forget to configure your application to use the handler. Add these lines to <httphandlers> section under <system.web> of web.config:

This took a 10kb css file down to about 7.9kb. For javascript, I was able to take the 130kb prototype.js library down to about 100kb. This may look like a small improvement, but scale that up to tens of thousands of users and it becomes significant.

Download the demo and source here.