From which version ?

We can use Bundling and minification from ASP.NET 4.5 (ASP.NET MVC 4). In MVC3 and Asp.Net 4.0 application we can utilize by including System.Web.Optimization.dll and WebGrease.dll reference to our projects  and we can create the bundle for .css and .js files with in the Global.asax file.

What is it?

Bundling: It’s a group of js and css files that could be referred by unique name.
Purpose: The main usage of bundling is, it being loaded with one HTTP request instead of multiple request for each file.

Minification : It’s main process is removing of unnecessary white-space from the js and css files.
Purpose: The main purpose is to remove line break and comments from code and improving load times by reducing its size of the file.

Work with Example: 

Let we start to discuss with the simple example of working process for bundling with js files.

Example 1: Without Bundling

Step :1

In our example, i had referred five following script files in the “index.cshtml” view.

Step :2

Run the application and see the output for the request in browser as shown below. Each files request make their own time. Totally they spend 513 millisecond to load all files(ie., 0.513 seconds).

bundling1-dotnet-helpers

From the above image, we understood the page request five time for loading script file . To reduce this loading time we have moving to bundling concept. Let we dicuss with sample exmple

Example 2: Using Bundling

Step :1

Instead of refering all the files in view, we moving them together in BundleConfig.cs file in App_Start folder like below

All the files has been included under the unique name dotnet-helpers-scripts.so if we want to call these all js files in view, then we will call using bundle file name “dotnet-helpers-scripts”

Step :2

Be aware these two things has been included in Application_Start method in Global.asax file in the application

Step :3

Here we calling the bundle dotnet-helpers-scripts which contain all 5 files. So here the request will only once while site loading

Step : 4

Run the application to see the output difference using browser debugger mode

bundling2-dotnet-helpers

Form above image, all files are bundled in one (ie., dotnet-helpers-scripts). Instead of loading five .js files, it has been loaded with single dotnet-helpers-scripts bundle. so its taking only 63 millisecond (0.063 second) to load.

Minification :

In same way we can also include the .css files in bundling. We need to remove all the white-space and commands as shown in below example

Example:

body{background-color: #fff;border-top: solid 10px #000;color:#333;font-size:.85em;font-family:”Segoe UI”, Verdana,Helvetica,Sans-Serif;margin:0;padding:0;}…..

For css we use @Styles.Render(“….”) instead of @Script.Render(“….”) and  bundles.Add(new StyleBundle(“~/Content/css”).Include(“~/Content/site.css”)) instead of  bundles.Add(new ScriptBundle(“~/bundles/jquery”).Include(“~/Scripts/…”));

Keep cool coding….