ASP.NET MVC Merge + Minify Javascript on the fly

According to Yahoo’s Best Practices for Speeding Up Your Web Site we should make fewer HTTP Requests.

I usually like to combines my images into a single *.png file and use CSS Sprites to display the image, or merge all my JavaScripts and Styles into a single js/css file.

This article is going to focus only on JavaScript and CSS minification/merging, but I might write another for images and sprites later.

I use this technique in all my project, it is very easy, lightweight and the best is it runs when you build your solution.

In this example I used:

  • Visual Studio 2010
  • .NET 4
  • ASP.NET MVC 3
  • Yahoo YUI Compressor
  • EcmaScript.NET

Step 1: Create a new MVC Project.

 

Step 2: Create some CSS and JS files.

In this case I simply split the Site.css that comes with MVC into many files and added a Site.js files that simply does on alert on document ready.

Step 3: Modify the MasterPage (_Layout.cshtml) to reference the right files depending on the solution running in Debug or Release.

Step4: Add the EcmacScript.NET and Yahoo.UI.Compressor binariesfrom the example file on Codeplex).

Step 5: Create MSBuild.xml file – start from Codeplex example



    

    
        
            ../AssetsMinification/Content/AssetsMinification.css
        
        
            ../AssetsMinification/Scripts/AssetsMinification.js
        
    

    

        
            
            
            
            
            
            

            
            
            
        

        
    

Step 5: Run It in release mode

That’s it!

Here’s the code.

This entry was posted on Tuesday, July 12th, 2011 at 5:30 pm and is filed under ASP.NET, CSS, JavaScript, MVC. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Responses to “ASP.NET MVC Merge + Minify Javascript on the fly”

Andrew Beaven August 9th, 2011 at 12:48 am

What codeplex project are you referring to?

Ray Linder (@RayLinder) December 4th, 2011 at 2:20 pm

To answer Andrew’s question & others to reference. The CodePlex project he’s referring to is the “Yahoo! UI Library: YUI Compressor for .Net” on CodePlex – http://yuicompressor.codeplex.com/

Leave a Reply