Remove whitespace from stylesheets and JavaScript files

Feb 12, 2006

There is a lot of whitespace in both stylesheets and JavaScript files. This is because of indented text and line breaks to name a few. They are typically also filled with comments to make them more maintainable. Believe it or not, it all adds up substantially to the overall file size. My tests show that stylesheets can be reduced by more than 30% and JavaScript files by 20%. That’s a lot.

I made two C# classes, which implement the IHttpHandler interface, one for stylesheets and one for JavaScript files. The easiest way to implement them is simply to add this line to the <system.web> section of the web.config.

<httpHandlers>
      <add verb="*" path="*.js" type="ScriptHandler" validate="false"/>
      <add verb="*" path="*.css" type="CssHandler" validate="false"/>
</httpHandlers>

You also have to make sure that the IIS lets the ASP.NET ISAPI filter handle files with .css and .js extensions.

The classes use regular expressions to remove whitespace and comments. Then it caches the cleaned file and adds a dependency to the real .css/.js file on disk. Every time you change the source file, the cache reloads.

In order to remove comments properly, you should use the /*  …  */ syntax and not //. Further more, it can be a problem for the JavaScript handler if a line isn’t closed with a semicolon. Enjoy.

httphandlers.zip (1,95 KB)* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Comments (4) -

Josh Stodola
Josh Stodola United States
10/25/2007 11:00:26 PM #

>> You also have to make sure that the IIS lets the ASP.NET ISAPI filter handle files with .css and .js extensions. <<

It would be awesome if you could elaborate on how to do this.

Best regards...

Josh Stodola
Josh Stodola United States
10/28/2007 12:43:35 AM #

Nevermind, I got it figured out.  I also changed it to recognize "CSS Naked Day".

Thanks dude!

ajit goel
ajit goel United States
11/30/2007 1:44:10 PM #

>> You also have to make sure that the IIS lets the ASP.NET ISAPI filter handle files with .css and .js extensions. <<

It would be awesome if you could elaborate on how to do this. Do I need to make changes using the IIS manager for my site??

Best Regards;

Ajit Goel

Rainynight
Rainynight Iran
4/4/2008 6:55:56 AM #

it conflict with CompressionModule Frown

Pingbacks and trackbacks (1)+

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.