Asp.Net MVC Bundling and Minification

  Total Views : 851
  Comments : 0
 
  Keywords : Asp.net mvc optimize and increase website performance using bundling and minification with example, Asp.net mvc javascript and css files bundling and minification with example

Here we will learn bundling and minification in asp.net mvc with example and how to optimize and improve performance of asp.net mvc website using bundling and minificaiton with example.

Asp.Net MVC Bundling and Minification

Let’s start with Understanding New Feature in MVC 4 is Bundling and Minification this feature helps us to reduce Overall Load time of Website.

 

While working in ASP.NET Webforms we use Master page to apply common design to all the pages in that we also use to add our Script reference and Css reference to page. There are many Script files like one for date picker, other for Image Popup, if use webcam in your application then we also need to add reference JavaScript of Webcam to on page, etc. same way we use CSS file references like one for date picker, different CSS for Image Popup and last for webcam, etc. by adding these many references on page think how much time will it take to load a simple page.

 

When we try to browse a website it will send http request to server to get single css file for date picker after that it will send request to get CSS for Image pop up gallery after that main site css and last for webcam, etc. it has sent total more than 4 requests to getting all css files to render. This same process will be carried out for script too for that also more than 4 requests will send to get this script so total more than 8 hits on server for getting only styles and script will sure affect load time.

 

To solve this problem Microsoft has come up with new features Bundling and Minification in mvc.

Bundling in Asp.Net MVC

In asp.net mvc bundling is used for grouping multiple script and styles such that it can be rendered in one single request from server.

 

Sending Multiple Request for getting Scripts and styles from server.

In this snapshot when User is accessing website from server the number of request are made to get files from server.

 

Sending single Request for getting Scripts and styles from server

 In this snapshot when user is accessing website from server but we are using asp.net mvc bundling for request that’s why only single request made to server and multiple files get return.

Minification in Asp.Net MVC

In asp.net mvc minification feature is used for removing unnecessary whitespace, line break and comments from Script and Css files such that it can reduces its size and decrease loading time of Website.

 

After understanding what is bundling and Minification now let’s start to implement it.

Create New Asp.Net MVC Application

To create new application in asp.net mvc first open visual studio from Start page select File à New à Project like as shown following image

 

create new asp.net mvc project from visual studio 2012

 

After that a new dialog pop up will open from that select Templates à Visual C# à Web à In project select ASP.NET MVC 4 Web Application and enter Name of Project “MVCBundleandMini” after this just click on OK button.

 

select asp.net mvc 4 web application from templates section

 

Now new ASP.NET MVC 4 Project dialog will appear from that select Internet Application Template and select view engine as Razor and and we are not going to Create Unit testing for this project hence do not check this option and finally click on OK button like as shown below

 

Select project template as internet applications in asp.net mvc application

 

Once we click OK button it will create new asp.net mvc application that would be like as shown below

 

Bundle and Minification project structure in asp.net mvc

Bundle in Asp.Net MVC Project Structure  

The Bundle is located in App_Start Folder of your Project. If you open App_Start Folder there you will find [BundleConfig.cs] in this file we will write all Bundling and Minification scripts.

 

Bundle Config File Location in Asp.Net MVC Application

 

After locating where bundle is stored now let’s open this file and check there are already some bundles created.

 

Bundle Config Default Code in Asp.Net MVC Application

 

Now let’s learn how to create a bundle. The BundleCollection is a Class and System.Web.Optimization is namespace in which it is located.

Create Script Bundle in Asp.Net MVC

To add new bundle we should write code inside class BundleConfig with RegisterBundles Method. We are going to create a bundle for scripts which we have selected in below snapshot.

 

Selected Scripts which we are going to use in Creating Bundle in mvc

Adding Script Bundle in Asp.Net MVC

First we are going to use object of bundles to add bundle.

Add bundles extension using add method in asp.net mvc

After that Add Method take Bundle as Input for that we have provide [newScriptBundle] as input.

Add new scriptbundle in Asp.Net MVC Application

 

After that [ScriptBundle] take Virtual path as input for that we have provide path ["~/TestBundle/Jqueryfiles"]. This path can be any path but must be simple to understand.

Add new scriptbundle virtual path in asp.net mvc application

After providing Virtual path new let’s provide all Script files VirtualPaths which we want to render.

Add all virtual paths to render all bundle files in asp.net mvc

Following is the complete code snippet of bundle in asp.net mvc application.

 

public static void RegisterBundles(BundleCollection bundles)

{

 bundles.Add(new ScriptBundle("~/TestBundle/Jqueryfiles").Include(

"~/Scripts/modernizr-2.6.2.js",

"~/Scripts/jquery-1.8.2.js",

"~/Scripts/jquery.unobtrusive-ajax.js",

"~/Scripts/jquery.validate.js"

));

}

Finally, after completing with Adding VirtualPaths now Let’s Add Controller and View for testing how this ScriptBundle render on view.

Adding Controller in Asp.Net MVC

To add controller just right click on Controller folder then select Add from list and inside that select controller.

 

Add new controller to asp.net mvc application

 

After selecting controller, a new dialog will pop up with name Add Controller.

 

Give name to controller and select empty mvc controller template

 

Now let’s name this controller as Default1Controller and in template we are going to select Empty MVC controller. Finally click on Add button to create Default1Controller.

Complete code of Default1Controller

Following is the code snippet of Default1Controller in asp.net mvc application.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace MVCBundleandMini.Controllers

{

public class Default1Controller : Controller

{

//

// GET: /Default1/

 

public ActionResult Index()

{

return View();

}

 

}

}

Adding View Index in Asp.Net MVC

For adding view you just need to right click inside Action Method Index a new Dialog will Pop up with Name Add View. Following is the  snapshot of it.

 

Add New View to Index Action Method in Controller in Asp.net MVC Application

 

In above dialog the View Name will be similar to Action Method and then View engine will be Razor default. After that in scaffold template we are not going to select any Template and finally click on Add button. Following is the snapshot after adding View.

 

Project structure after adding view in asp.net mvc application

 

Following is the complete code of newly added index view.

 

@{

Layout = null;

}

 

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width"/>

<title>Index</title>

</head>

<body>

<div>

 

</div>

</body>

</html>

Calling Script Bundle on View in MVC

To render script on View we are going to use @Scripts helper and provide Virtual path reference which we have added in BundleConfig that will be like as shown below

 

@Scripts.Render("~/TestBundle/Jqueryfiles")

 

@{

Layout = null;

}

<!DOCTYPE html>

@Scripts.Render("~/TestBundle/Jqueryfiles")

<html>

<head>

<meta name="viewport" content="width=device-width"/>

<title>Index</title>

</head>

<body>

<div>

</div>

</body>

After adding Script to render now Save and Run Application without enabling optimizations and Access URL - http://localhost:xxxx/Default1/index

 

To debug how many Scripts are loaded you can press F12 in browser [Developer Tools] for now we are using chrome browser to access this url. And press F12 to debug it.

 

Now to check load time click on Network tab and press F5 to reload page to get time log.

 

Accessing Index View without Enabling Optimizations

 

Now if you check there are 5 request made to Server to get page and Script. You might think we have created bundle but it's not working still we have 5 requests to server. To make it work we need to enable optimization.

 

To Enable optimization we have to add [BundleTable.EnableOptimizations = true;] in BundleConfig Class. Following is the complete code snippet after enabling optimization.

 

using System.Web;

using System.Web.Optimization;

 

namespace MVCBundleandMini

{

public class BundleConfig

{

public static void RegisterBundles(BundleCollection bundles)

{

bundles.Add(new ScriptBundle("~/TestBundle/Jqueryfiles")

.Include(

"~/Scripts/modernizr-2.6.2.js",

"~/Scripts/jquery-1.8.2.js",

"~/Scripts/jquery.unobtrusive-ajax.js",

"~/Scripts/jquery.validate.js"

));

 

BundleTable.EnableOptimizations = true;

}

}

}

We enabled optimization in script modeul now Save and Run the application. If you check there are 2 request made to Server to get page and Script.

 

. Accessing Index View with Enabling Optimizations

Minified Script in Asp.Net MVC

In below snapshot if you check the URL of Script Bundle which we have created is rendered for all script Files.

 

Minified Script ULR in Asp.Net MVC Application

 

Now we have completed with Adding Script Bundle. If you copy Requested URL from above developer tool and check in browser it is minified. You will not find whitespace Comment in this File.

 

URL - http://localhost:2433/TestBundle/Jqueryfiles?v=j2iHmiYwmE-Q993EjXcLXhvnT2P43QJ6Ljr0GDJisvQ 

 

Minified Script in Asp.Net MVC Application

Create Style Bundle in Asp.Net MVC

Now we are going to use following selected CSS files to create style bundle.

 

Selected style sheets we used to create bundle in asp.net mvc

Adding Style Bundle in Asp.Net MVC

First we are going to use object of bundles to add bundle.

Add bundles extension using add method in asp.net mvc

 

After that Add Method take Bundle as Input for that we have provide [newStyleBundle] as input.

Add new style bundle in Asp.net mvc application

After that [StyleBundle] take Virtual path as input for that we have provide path ["~/TestContent/css"]. This path can be any path but must be simple to understand.

Mention Virtualpath in New StyleBundle in Asp.net MVC Application

After providing Virtual path new let’s provide all Css files VirtualPaths which we want to render.

Include all css files to bundle in asp.net mvc application

Following is the complete code snippet of Style bundle

 

public static void RegisterBundles(BundleCollection bundles)

{

bundles.Add(new StyleBundle("~/TestContent/css")

.Include(

"~/Content/site.css",

"~/Content/site1.css",

"~/Content/site2.css",

"~/Content/site3.css"

));

}

Code Snippet of BundleConfig

Following is the complete code snippet of BundleConfig file.

 

using System.Web;

using System.Web.Optimization;

 

namespace MVCBundleandMini

{

public class BundleConfig

{

public static void RegisterBundles(BundleCollection bundles)

{

bundles.Add(new ScriptBundle("~/TestBundle/Jqueryfiles")

.Include(

"~/Scripts/modernizr-2.6.2.js",

"~/Scripts/jquery-1.8.2.js",

"~/Scripts/jquery.unobtrusive-ajax.js",

"~/Scripts/jquery.validate.js"

));

 

bundles.Add(new StyleBundle("~/TestContent/css")

.Include(

"~/Content/site.css",

"~/Content/site1.css",

"~/Content/site2.css",

"~/Content/site3.css"

));

}

}

}

Calling Style bundle on View 

To render Style on View we are going to use @Styles helper and provide Virtual path reference to it which we have added in BundleConfig that would be like as shown below.

 

@Styles.Render("~/TestContent/css")

 

@{

Layout = null;

}

 

<!DOCTYPE html>

 

@Scripts.Render("~/TestBundle/Jqueryfiles")

 

@Styles.Render("~/TestContent/css")

 

<html>

<head>

<meta name="viewport" content="width=device-width"/>

<title>Index</title>

</head>

<body>

<div>

 

</div>

</body>

</html>

Now we will run application without enable optimization in style bundle. If you check below snapshot, there are 9 request made to get Css and Script files along with page.

 

Accessing Index View without Enabling Optimizations [Style]

 

Now we will run application by enabling optimization in style bundle using following property.

 

BundleTable.EnableOptimizations = true;

Now if you check there are 3 request made to Server to get page and Css, Script.

 

Accessing Index View with Enabling Optimizations [Style]

Minified Style [Style bundle]

In below snapshot if you check the URL of Style Bundle which we have created is rendered for all Css Files.

 

Rendered Style Sheet URL in Asp.Net MVC Application

 

If you copy Request URL from above developer tool and check in browser it is minified. You will not find whitespace Comment in this File.

 

URL - http://localhost:2433/TestContent/css?v=0AMQo07q8rol6iXCFEG6BHahzWOWJ7In7_k0vciOzBM1

 

Minified Style Sheet in Asp.net MVC Application

 

Note: - Use .js file in Debug Mode and .min.js file in Release Mode.

Files in debug and release mode in asp.net mvc application

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User