Tag Archives: Minify

Asp.Net MVC

Minify CSS & JS With MVCContrib

I was doing a bit of research recently trying to find a way to compress, combine and minify css and js in Asp.Net MVC 2 and found a few ideas on the subject. The one that caught my eye was the MvcContrib IncludeHandling; a little hidden gem.

Getting it up a running however wasn’t so straight forward (there isn’t much documentation about it, or at least not much I could find.). The first problem I stumbled upon was the HtmlExtensions (RenderIncludes function) required a dependency resolver which the project I was on didn’t use. To get round this I simply copied the source (from the HtmlExtensions link) and replaced the dependency resolver with the projects IoC framework (in this case we’re using MvcTurbine with Ninject)

Next you need to register the dependency with your IoC of choice, like I said previously we’re using MvcTurbine so this is how I did with with a service registration.

namespace YourProject.MvcSite.Registration
  using System.Web;
  using MvcContrib;
  using MvcContrib.IncludeHandling;
  using MvcContrib.IncludeHandling.Configuration;
  using MvcTurbine.ComponentModel;

  /// <summary>
  /// Regisers the minify interfaces
  /// </summary>
  public class MinifyRegistration  : IServiceRegistration 
    /// <summary>
    /// Registers the components with the specified <see cref="T:MvcTurbine.ComponentModel.IServiceLocator"/> instance.
    /// </summary>
    /// <param name="locator">Instance of <see cref="T:MvcTurbine.ComponentModel.IServiceLocator"/> to use.</param>
    public void Register(IServiceLocator locator)
      var httpContext = new HttpContextProvider(HttpContext.Current);
      var handler = new IncludeHandlingSectionHandler();
      var reader = new IncludeReader(httpContext);
      var storage = new StaticIncludeStorage(new KeyGenerator());
      locator.Register<IIncludeCombiner>(new IncludeCombiner(handler, reader, storage, httpContext));

The final step is to select the js/css files you want and then combine them. In the example below we’re using the T4MVC template to generate the static file links which and the code is used in a view (in our example it’s the site master view).

      var scripts = new List<string>
                        "~" + Links.Scripts.jquery_1_4_2_min_js,
                        "~" + Links.Scripts.jquery_ui_1_8_2_custom_min_js,
                        "~" + Links.Scripts.jquery_localscroll_1_2_7_min_js,
                        "~" + Links.Scripts.jquery_scrollTo_1_4_2_min_js,
                        "~" + Links.Scripts.jquery_serialScroll_1_2_2_min_js,
                        "~" + Links.Scripts.Ajax_js,
                        "~" + Links.Scripts.Custom_js,
                        "~" + Links.Scripts.json2_js,
                        "~" + Links.Scripts.flowplayer_3_2_3_min_js,
                        "~" + Links.Scripts.DragDrop_js,
                        "~" + Links.Scripts.Slider_js