Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine, minimize and gzip for CSS and JavaScript files for ASP.NET MVC

Good day!

I'm looking for solution to combine, minimize and gzip CSS and JavaScript files. It seems they come in two forms:

  • In form of ASP.NET handler\module with processing files on the fly (with caching results)
  • In form of VS build tasks (to perform processing while building)

Generally I'm ok with either.

I've looked on a number of solutions (and I use ASP.NET handler from this article http://www.codeproject.com/KB/aspnet/httpcompression.aspx a lot), but maybe something "must have" came out and I've missed it.

Thanks in advance!

like image 716
artvolk Avatar asked Jan 10 '11 21:01

artvolk


2 Answers

Here's my advice to you: use build tasks and HTTP cache the output.

In terms of build tasks, you'll want to check out your favorite JavaScript minifier (my favorite is Google Closure Minifier) that has a command line utility that you can just plug into your project file, MSBUILD file or NANT file. Same deal with CSS (I personally use Yahoo! YUI Compressor). If you're into using LESS, you can certainly combine this with the YUI compressor. To optimize images, I'd use optipng. There's directions on how these guys work on their individual sites.

Now, after you have these files all nice and optimized, you'll want to output them using a handler or controller action for MVC. To set the expiration so that subsequent requests will default to the file downloaded on the first request, you'll want this to run in your code:

Response.ExpiresAbsolute = DateTime.Now.AddYears(1);

More than likely you'll want a cache-buster strategy so that you can change the content files. You'd do this by passing a random parameter to your handler. There are a few different ways to go about this... just Google it.

Hope this helps.

like image 178
zowens Avatar answered Sep 25 '22 03:09

zowens


I'm using the telerik mvc components for small-medium sites. It was simple to add and configure with NuGet.

like image 40
Brian Cauthon Avatar answered Sep 22 '22 03:09

Brian Cauthon