Using SquishIt with Razor – ASP.Net MVC3 and MVC4

1 minute read

I’ll assume you already know the reasons why you should minify and combine your CSS and Javascript.

My favourite of the tools available for .Net is SquishIt by Justin Etheredge - here’s how I hook it up in my ASP.Net MVC4 (and MVC3) Razor projects..

  1. Get the bits, either directly or find it in NuGet
  2. Add a Project Reference to the SquishIt.Framework.dll
  3. Add SquishIt to the namespaces section in the Views/Web.config:
<system.web.webPages.razor>
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      ..
      <add namespace="SquishIt.Framework" />
      ..
    </namespaces>
  </pages>
</system.web.webPages.razor>
  1. Replace any `<link />` and `<script />` references with the following*:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE html>
<html>
  <head>

  ..

  @MvcHtmlString.Create(
    Bundle.Css()
      .Add("/Content/Styles.css")
      .Add("/Content/MoreStyles.css")
      .Render("/Cache/Styles-combined.css"))

  @RenderSection("css", false)

  @MvcHtmlString.Create(
    Bundle.JavaScript()
      .Add("/Scripts/SomeScript.js")
      .Add("/Scripts/SomeOtherScript.js")
      .Add("/Scripts/YetAnotherScript.js")
      .Render("/Cache/Scripts-combined.js"))

  @RenderSection("js", false)

  ..

  </head>

Note: I'm loading the `<script />`'s in the `<head />` here for brevity, but there's nothing stopping us moving these two JavaScript statements to the bottom of our page so they're just above the closing `</body>` as is generally recommended

  1. Finally, as you'll have noticed in lines 11 & 20, we're generating the squished files to a /Cache directory, so we need to create it and grant the IIS AppPool our site is running under create and modify permissions to it

As I’m usually working with Layout pages, I’m sure you’ll have also noticed the @RenderSection()’s in the example (lines 13 & 22) - that let’s me inject page-specific Squished CSS and/or Javascript as needed like so:

@section css {
  @MvcHtmlString.Create(
    Bundle.Css()
      .Add("/Content/PageSpecificStyle.css")
      .Render("/Cache/PageSpecificStyle-combined.css"))
}

@section js {
  @MvcHtmlString.Create(
    Bundle.JavaScript()
      .Add("/Scripts/PageSpecificScript.js")
      .Add("/Scripts/AnotherPageSpecificScript.js")
      .Render("/Cache/PageSpecificScript-combined.js"))
}

Thank you Justin 🙂

Updated: