6 Comments

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)

Comments

Comment by Josh Stodola

>> 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...

Comment by ajit goel

>> 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

ajit goel