sábado, 14 de enero de 2012

Using SquishIt in an ASP.Net MVC3 web application.

SquishIt is a fantastic library that allows you to easily combines all of your CSS files into a single file and also minifies it to boot! It also does the same thing on your Javascript.

Check out the difference:

SquishIT comparison MVC3

Let's see how to use it in an ASP.Net MVC3 application.



First we need to download the actual library. The easiest way to get it is using the NuGet package. In your MVC3 project, right click on References and select Manage NuGet Packages.

SquishIT comparison MVC3

Search for SquishIt.Mvc and add it to your project references. It'll configure it for you.

SquishIT comparison MVC3

Next, we need to reference the library namespace in our _Layout.cshtml file.

[sourcecode language="html"]
@using SquishIt.Framework
@using SquishIt.Mvc

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
[/sourcecode]

Now inside the head element, let's use SquishIt to minify and compress our code.

[sourcecode language="html"]
<head>
<title>@ViewBag.Title</title>
<link rel="SHORTCUT ICON" HREF="@Url.Content("~/Public/images/favicon.ico")">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
@(Bundle.Css()
.Add("~/Public/stylesheets/normalize.css")
.Add("~/Public/stylesheets/mainstyle.css")
.Add("~/Public/stylesheets/jQueryUI/jquery-ui-1.8.16.custom.css")
.ForceRelease()
.MvcRender("~/Public/stylesheets/combined_#.css")
)
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
</head>
[/sourcecode]

What's going on is, first your CSS files are being minified. Right there you save a ton of space. Next the minified collection of strings are persisted to a single .css file. Notice how there is a _# symbol at the end.

That's there for hashtag purposes. If you change a single letter in your CSS that hash is changed and the client browser have to request a new .CSS file. If you haven't changed a thing, the result is cached and your users don't need a new version.

And that's all there is to it! It's really that simple. The bigger your project the more you will save in transferred data and GET requests. The compressed files are also automagically cached so there is very little overhead.

I'm already using this on client websites and have had great result so far.

1 comentario:

  1. You should also check out Cassette. It's quite similar, but is highly configurable, and let's you bundle things up in a config file, reducing the amount of code you need to include in your .cshtml files.

    ResponderEliminar