Sunday, July 08, 2012

Delivering Compressed and Combined files for MVC 3 applications

It is very difficult to stay in the race without delivering application that performs “The Best” in the web world. To help us be in the race, we have lot of resources available in the internet to search for and plug in to our web application to gain optimal performance. One such tool is Squish It.

SquishIt is a framework for ASP.NET web application that compresses and combines javascript and css files. There are lot more options available with the SquishIt framework, but let’s walk-through the quick process of setting up the framework for ASP.NET MVC 3 application to compress and combine the css and javascript files.

Ok here we go…

1.       Download the latest framework from the GitHub from the following location: https://github.com/jetheredge/SquishIt/downloads

2.       Extract the zip file and reference the SquishIt.Framework.dll and SquishIt.Mvc.dll in your MVC application.
Note: If the dlls are not available in the bin folder of the extracted zip file, then you will have to open the solution in VS and built it (in release mode) and then reference the dlls in your MVC application.

3.       Next open the page (cshtml) where you have references to javascript and css files

4.       Add the following library references at the top of the cshtml page:

@using SquishIt.Framework
@using SquishIt.Mvc

5.       Next we have to transform the code that references the css files from:

<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
       <link href="@Url.Content("~/Content/ jquery.alerts.css")" rel="stylesheet" type="text/css" />
       <link href="@Url.Content("~/Content/bootstrap.css")" rel="stylesheet" type="text/css" />

                to

                @(Bundle.Css()
            .Add("~/Content/Site.css")
            .Add("~/Content/jquery.alerts.css")
            .Add("~/Content/bootstrap.css")
            .ForceRelease()
            .MvcRender("~/Content/Site_#.css")
       )

6.       And then we transform the code that references the javascript files from:

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>

                to           

       @(Bundle.JavaScript()
            .Add("~/Scripts/jquery.validate.min.js")
            .Add("~/Scripts/jquery-ui-1.8.11.min.js")
            .Add("~/Scripts/MicrosoftAjax.js")
            .ForceRelease()
            .MvcRender("~/scripts/combined_#.js")
)

And that’s it! Go ahead and run your application. Open the Firefox YSlow plugin and verify the number of requests for the css and javascript files. It should be two. Also, you would find that the size of the output file is a reduced one.

Happy programming!!!


No comments: