In this article, I will explain you about Bundling and minification in asp.net MVC C#, which help's us reduce page load time by combining all the scripts and stylesheet into one file and decreasing its size.

Meaning of Bundling and Minification?

Bundling and minification techniques were introduced in MVC 4 to improve server request load time. Bundling allows us to load the bunch of static files from the server into one HTTP request, while Minification technique optimizes script or CSS file size by removing unnecessary white space and comments and shortening variable names to one character.

Why do we need bundling and minification?

Basically, when developers create web-application using CSS and JavaScript, they create multiple files of JavaScript and CSS, to load each of this file, browser sends requests to server multiple times, so to reduce the multiple requests we combine these files and create one unique file with the help of bundling technique, thus it reduces requests while removing extra spacing, comments,line-breaks etc from files is called minification technique, which reduces size of file, with the help of both technique page loads faster and gives better user experience.

bundling-and-minification-MVC-C#

The bundle is a logical group of physical files, which loads in a single HTTP request. We usually have separate CSS files placed in Content folder of our MVC project, which can be loaded in a single request with the help of bundling. The bundling also can create for JavaScript files separately. A bundle can’t contain both CSS and JavaScript files.

So, bundling helps us reduce the number of HTTP Requests and payload size resulting in faster and better performing ASP.NET MVC Websites.

Steps to Achieve it:

To get started with bundling in MVC, you’ll need to perform a few straight forward steps:

  1. Create a bundle configuration to instruct MVC how to combine and compress (minify) your files.
  2. Register your bundle configuration with your Web application.
  3. Add a reference to your bundle to your MVC views.

Creating Bundle Configuration

By default, the MVC application's BundleConfig (located inside App_Start folder) comes with similar code as below −

public static void RegisterBundles(BundleCollection bundles) { 

     //Code to bundle Javascript files
     bundles.Add(new ScriptBundle("~/Scripts/jquery").Include(
                        "~/Scripts/jquery-1.10.2.min.js",                     
                        ));    
          
   // Code to bundle CSS files
  
   bundles.Add(new StyleBundle("~/Content/themes/base/css").Include( 
      "~/Content/themes/base/jquery.ui.core.css", 
      "~/Content/themes/base/jquery.ui.tabs.css", 
      "~/Content/themes/base/jquery.ui.datepicker.css",  
      "~/Content/themes/base/jquery.ui.progressbar.css", 
      "~/Content/themes/base/jquery.ui.theme.css")); 


}

MVC provides two tailored classes for our purposes:ScriptBundle for JavaScript files, and, StyleBundle for CSS. Both of these classes provide built-in minification, thus reducing your total payload even further. You’ll need to specify a unique path for each bundle, which we’ll use to output references to our MVC views later.

var myBundle = new ScriptBundle("~/Scripts/jquery");

Using this bundle, you can simply add new files (or entire directories!) by using its methods:

myBundle.IncludeDirectory("~/Scripts/vendor/");
myBundle.Include("~/Scripts/app.js");

A nice feature of these methods is that you can specify your paths as “app-relative”—that is, relative to the root of your application, whether it be in a subfolder or not—with the “tilde” notation. Thus, “~/Scripts/app.js“ might become “localhost:1234/Scripts/app.js“ in development and “www.testapp.com/Scripts/app.js“ in production.

Once you’re done with each bundle, add it to the collection passed in as a parameter (in this example, we’ve called it bundles):

 bundles.Add(myBundle);

Continue this pattern until you’ve configured all of the bundles you’d like.

MVC 5 includes following bundle classes in System.web.Optimization namespace:

ScriptBundle: ScriptBundle is responsible for JavaScript minification of single or multiple script files.

StyleBundle: StyleBundle is responsible for CSS minification of single or multiple style sheet files.

DynamicFolderBundle: Represents a Bundle object that ASP.NET creates from a folder that contains files of the same type.

Using the "*" Wildcard Character in bundling

"*" wildcard character is used to combines the files that are in the same directory and have same prefix or suffix with its name. Suppose you want to add all the scripts files that exist with in "~/Script" directory and have "jquery" as prefix then you can create bundle like below:

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/Scripts/jquery*.js"));

similar you can achieve this to add all the css that exist with in "~/Content" directory

 bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/*.css"));

Register the bundle configuration

Now go to your Global.asax file, in Application_start method add these lines of code to register your bundle and for minification

protected void Application_Start()
{
            //[Other code]


            //To resgiter bundling
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            //To enable minification
            BundleTable.EnableOptimizations = true;
}

Referring Bundles in views

Normally, we use common _layout.cshtml file to reduce duplication and place all the common code in one file, which is placed under Shared folder of Views by default.

Inside this file, all that’s needed to output your bundled reference is the following:

@System.Web.Optimization.Styles.Render("~/Content/theme/base/css")
@System.Web.Optimization.Scripts.Render("~/Scripts/jquery")

Note that the string argument passed in here needs to match the path of a bundle we created earlier.

A nice built-in feature of bundling is that if debug="true" is defined in your Web.config file (meaning you’re running your application in “debug” mode) the bundler will output each file individually as if no bundling had occurred, which is useful for debugging purposes, as combined and minified JavaScript or CSS is practically unusable.So, remember to make debug=false while publishing your web-application.

That's it, we are done, now our page will load much faster, as JavaScript/CSS file size are reduced, plus requests to the server is also reduced by combining all the files into one virtual file each for javascript and CSS.