Some weeks ago I wrote how to minify and compress the WebResource.axd handler. In the comments of that post someone asked how to do the same with ScriptResource.axd. I thought about it and realized it could be done much smarter.
If you take a look at the HTML source at the CodePlex Issue Tracker page, you’ll see it references 13 WebResource.axd and ScriptResource.axd. That’s 13 different web requests on each page load. The ScriptResource.axd is using HTTP compression but WebResource.axd does not. None of them minifies the scripts.
How it works
To make it work, we need both an HttpModule and an HttpHandler.
The module looks for resource scripts in the HTML code and collects all the references from the src tag. It then constructs a new script tag containing all the references and points it to the HttpHandler. The new script tag is injected into the HTML where the first resource script was found. It keeps the order of the scripts intact.
All the original scripts are now removed and a single new script pointing to the handler is injected.
When the handler is requested by the browser it looks for a URL parameter containing the references to the original resource script. They are separated by a comma in the URL parameter. It then retrieves the content of each script using a HTTP request. Then content is then aggregated into a single string which then get’s minified. Minifying means that all comments and whitespace is removed from the script.
The string is then being cached so the handler only has to do it once per application life cycle. The output is then compressed and the appropriate header set so the browser will cache the file for 30 days. You can easily set the number of days in cache to whatever you see fit.
Download the ScriptCompressor.cs file below and put it in your App_Code folder. Then add the following lines to your web.config:
<add type="ScriptCompressorModule" name="ScriptCompressorModule" />
<add verb="*" path="*js.axd" type="ScriptCompressorHandler" />
ScriptCompressor.zip (3.43 kb)* $4.95/month ASP.NET Hosting with FREE SQL 2012 DB! – Click Here!