X

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 combine After combine Difference (before/after)
Requests 21 4 5.25
Size (kb) 259 19 13.63
Time (s) 7.69 4.84 1.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.

Liked this post? Empower your friends by sharing it!
Categories: ASP.NET

View Comments (9)

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

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

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

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

  • 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");

  • 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

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

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

Related Post