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

Josh Stodola

&gt;&gt; You also have to make sure that the IIS lets the ASP.NET ISAPI filter handle files with .css and .js extensions. &lt;&lt; It would be awesome if you could elaborate on how to do this. Best regards...

Josh Stodola

Josh Stodola

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

Josh Stodola

ajit goel

&gt;&gt; You also have to make sure that the IIS lets the ASP.NET ISAPI filter handle files with .css and .js extensions. &lt;&lt; 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

pimp.webdevelopernews.com

Pingback from pimp.webdevelopernews.com Removing Whitespace From Your Pages With ASP.NET

pimp.webdevelopernews.com

aspnet.deveronline.com

Pingback from aspnet.deveronline.com Resource (JS, CSS) compression, minification, and versioning | Asp.Net developed Tutorials | Asp.Net Developed Tutorials

aspnet.deveronline.com

Comments are closed