Minifying and Combining Multiple JavaScript Files in ASP.NET

Newer Web technologies make all kinds of new features possible, but with them come additional file bloat, slowing down your websites. Browsers can only download a limited number of files simultaneously, and all file requests that come afterward are stalled until the others are done. Fortunately, by compressing your files and combining them into a single file, you can greatly improve your site’s performance.

I recently found an ASP.NET solution that automatically minifies and combines your JavaScript files. You can read the article yourself for an in-depth look at the code, but I figured I’d post the basic steps here as a reminder to myself in future projects.

Step 1

Download the files, and extract them to the appropriate folders in your website project (create them if they don’t exist).

Step 2

Modify the file at App_Data/Site_Scripts.txt to include the scripts you want to combine, each on a separate line. If you have more than one set of scripts to combine, you can create more .txt files — just make sure they have unique file names.

Step 3

You’ll need to make some changes to your web.config file. Update the following sections, or create them if they are missing.

For IIS7:

<configuration>
   <system.webServer>
      <handlers>
         <add name="ScriptCombiner" verb="POST,GET" path="ScriptCombiner.axd" preCondition="integratedMode" type="ScriptCombiner, App_Code"/>
      </handlers>
   </system.webServer>
</configuration>

For IIS6:

<configuration>
   <system.web>
      <httpHandlers>
         <add verb="POST,GET" path="ScriptCombiner.axd" type="ScriptCombiner, App_Code"/>
      </httpHandlers>
   </system.web>
</configuration>

Step 4

Add the following to your Web form or master page, where the JavaScript files would normally appear.

<asp:Literal ID="jsLiteral" runat="server"/>

And, add the following to your code-behind in the Page_Load event.

jsLiteral.Text = ScriptCombiner.GetScriptTags("Site_Scripts", 1);

The first argument passed to the GetScriptTags method is the file name for your .txt file in the App_Data folder. The second argument is a version number. The version number appends a query string so that browsers know not to serve the file from cache (remember to update the version number when you update your JS).

And That’s It!

You should now be able to preview your page and see that all of your JS files have been combined and minified. If not, make sure you aren’t in debug mode (<compilation debug="false"/>). When in debug mode, files are not combined, but a query string is still added for the version number.