ASP.NET MVC: How to combine scripts and other resources

ASP.NET pages that use AJAX components make usually many requests to server per one page to load all required JavaScript and CSS files. Connections, like all other real time resources, are most expensive to create and keep. If we can somehow decrease the number of requests per page load then we need less server resources for same amount of users. For ASP.NET forms we can use script combining, for ASP.NET MVC applications we can use ASP.NET MVC Client-side Resource Combine.

MVC Resource Combine is open-source project you can find in CodePlex. ASP.NET official ScriptManager needs server-side form as a container. This means that all scripts are loaded in the body of page. I have found no way how to make ScriptManager to create script and other references to page header. MVC Resource Combine is free of this problem.

MVC Resource Combine is easy to use. Just follow these steps.

  1. Download the latest release and add references to DLL-s of MVC Resource Combine.
  2. Add the following line to web.config file, under <configSections> element:
    <section name="resourceCombine" type="Mvc.ResourceCombine.ConfigSectionSetting, 
    Mvc.ResourceCombine"
     
    />
  3. Add the following line to web.config file, under <configuration> section:
    <resourceCombine definitionUrl="~/App_Data/combine.xml" />
  4. Now open Global.asax and add the following line before all the other route definitions:
    routes.AddResourceCombineRoute("Resource Combine");
  5. To App_Data folder add new XML-file combine.xml. By example, for jqGrid you may have JavaScript resource set like this:
    <?xml version="1.0" encoding="utf-8" ?>
    <
    resourceCombine url="~/combine.axd" defaultDuration="15"
     
     
    defaultVersion="1" >
      <resourceSet name="jqGrid" type="js" duration="30"
     
     
    version="a">
        <resource path="~/Scripts/jquery-1.3.2.js"
     
         
    mode="LocalStatic" />
        <resource path="~/Scripts/jquery.jqGrid.js"
     
         
    mode="LocalStatic" />
        <resource path="~/Scripts/js/jqModal.js"
     
         
    mode="LocalStatic" />
        <resource path="~/Scripts/js/jqDnR.js"
     
         
    mode="LocalStatic" />
        <resource path="~/Scripts/jquery.ajaxQueue.js"
     
         
    mode="LocalStatic" />
        <resource path="~/Scripts/jquery.bgiframe.min.js"
     
         
    mode="LocalStatic" />
        <resource path="~/Scripts/thickbox-compressed.js"
     
         
    mode="LocalStatic" />
        <resource path="~/Scripts/jquery.autocomplete.js"
     
         
    mode="LocalStatic" />
      </resourceSet
    >
    </
    resourceCombine
    >
  6. Now open Site.Master and add call for MVC Resource Combine and specify resource set by its name (jqGrid):
    <%= Html.CombinerLink("jqGrid")%>
  7. Now run your application and view page source. You should see something like this:
    <script type="text/javascript" src="/combine.axd/jqGrid/a">
    </
    script
    >

NB! Don’t forget to add reference to Mvc.ResourceCombine namespace in your Global.asax and Site.Master files. Well, if you have Resharper, then it is almost possible to forget these references. :)

Now, let’s see results. It’s Saturday and I’m watching Estonian biggest song contest, so I’m too lazy to add Firebug screenshots here. I have a little bit different configuration but numbers in the following table should give you some idea about wins in performance.

 Before combineAfter combineDifference (before/after)
Requests2145.25
Size (kb)2591913.63
Time (s)7.694.841.59

As you can see, using MVC Resource Combining it is possible to achieve better performance with pretty simple and time consuming efforts. Also you don’t have to mix ScriptManager and other ASP.NET forms elements to your ASP.NET MVC views. By the way, you can combine also all the other resources that can be downloaded as one file – by example, style sheets.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    10 thoughts on “ASP.NET MVC: How to combine scripts and other resources

    • July 17, 2009 at 1:49 am
      Permalink

      Any idea how to incorporate this into a unit testing framework? I’ve only just started using NUnit, Moq etc., and all of my inbound and outbound routing tests now fail with
      RouteTable.Routes.AddResourceCombineRoute(“Resource Combine”);
      in global.asax.cs

      I’m not sure what I need to do in my unit tests to mock this facility to make sure my tests pass again.

    • July 17, 2009 at 1:58 pm
      Permalink

      Can you paste here the error message and error trace?

    • July 17, 2009 at 5:15 pm
      Permalink

      It seems like something wants to detect current HttpContext.

      // You have to create mock for this one because you
      // cannot instantiate it (abstract)
      var req = new HttpWorkerRequest();

      var con = new HttpContext(req);
      System.Web.HttpContext.Current = con;

      If there are more problems to be fixed then please let me know.

    • July 18, 2009 at 3:33 pm
      Permalink

      I take it this is supposed to go in TestRoute, but the line:
      var req = new HttpWorkerRequest();
      results in the error:
      “Cannot create an instance of the abstract class or interface ‘System.Web.HttpWorkerRequest'”

      Thanks for your help so far. I’m so confused by Moq and Unit Testing!

    • July 18, 2009 at 6:40 pm
      Permalink

      Yes, you cannot create HttpWorkerRequest. Create a mock object for this and use it. Mock object should do the work.

      You can also create fake HttpWorkerRequest (it’s a lot more work for you). In this case you have to create a class that extends HttpWorkerRequest and implements all abstract methods and properties.

      Third option is to turn off resource combining for tests. It should be the easiest thing you can do because in the tests you don’t need JavaScript and other client side resources.

    • July 20, 2009 at 5:06 pm
      Permalink

      Thanks so much for your help so far. I hate to give up on something but I think that turning it off for unit testing sounds the easiest! But how do I do that? The error is happening in global.asax.cs, which is presumably being compiled into the Web site dll, which the unit testing framework is using. How can I get global.asax.cs to ignore the line that sets up the script combiner? How do I detect that I don’t need to call:
      RouteTable.Routes.AddResourceCombineRoute(“Resource Combine”);

    • July 24, 2009 at 9:56 pm
      Permalink

      I suppose you run tests using Test configuration (you can set it from Visual Studio IDE). In this case preprocessor directive #DEBUG will be defined. You can do something like this in your code:

      #if !DEBUG
      RouteTable.Routes.AddResourceCombineRoute(“Resource Combine”);
      #endif

      Be warned that in this case resource combining is turned off also when you run your application in debug mode (you are not testing it but running it on web server). You can also define test configuration and define TEST constant. Then you can make check like this:

      #if !TEST
      RouteTable.Routes.AddResourceCombineRoute(“Resource Combine”);
      #endif

    • October 14, 2009 at 6:30 am
      Permalink

      I keep getting the error: Unrecognized configuration section resourceCombine.

      Also, I don’t see the file combine.axd in the download package, is this something I need to have in my project?

    • March 25, 2010 at 4:52 am
      Permalink

      Hi, is there a way to specify attributes like rel and title in the resource tag for css resources? Thank’s!!

    • Pingback:ASP.NET MVC Performance I: Combining resources | Gunnar Peipman - Programming Blog

    Leave a Reply

    Your email address will not be published. Required fields are marked *