In a project there may exists multiple CSS and JavaScript files. Bundling is a mechanism or concept of combining multiple JavaScript or CSS files into single file at run time.
Now, the question arises but why? why do we actually need bundling.
To understand the problem let's do a little demonstration.
Create three CSS files and two JavaScript files and include them either in the view page or Layout page like below.
Now run the application and press Ctrl+Shift+I to open chrome developer tool and go to Network tab and again send the same request (refresh the page) you will find multiple get requests like below.
As you can see, instead of single get request, there are multiple get requests, actually three are six requests going to the server one for Html (view) and three for CSS files and two for JavaScript files. Meaning for X number of CSS files and Y number of JS files, there will be X+Y number of Get requests, which is bad for performance.
The solution will be combining all CSS files into a single Style bundle and request it as a single request and similarly combining all JavaScript files into a single Script bundle and request it as a single request.This process is termed as bundling.
Minification
Minification reduces the size of JavaScript and CSS files by removing the comments, blank spaces etc.For example consider the below CSS file.
/*this is myclass style*/
.myclass{
background-color:red;
height:100px;
width:300px;
margin-bottom:5px;
border:1px solid black;
}
As you can observe ,the CSS properties are defined in multiple lines which increases the file size .The file has a comment too.
After implementing minification the above css files looks like below.
.myclass{background-color:red;height:100px;width:300px;margin-bottom:5px;border:1px solid #000}
you can see whitespaces and comments are removed and codes of multiple lines has changed to single aline ,which minimizes the file size and thus increases performance.
How to implement bundling and Minification
You have to follow exactly 2 steps to implement bundling and minification.
Step 1.Open BundleConfig.cs under App_Start folder in your application.And include all your necessary CSS files into a Style bundle and all necessary JS file into Script bundle and add them to the bundle collection like below.
Step 2.Go to Global.asax and add following statement under Application_Start event to actually enable bundling and minification.
BundleTable.EnableOptimizations = true;
Now you might be wondering who actually calls the RegisterBundles() method of BundleConfig class and when it is called.
Actually whether it be Route registration, Area registration or bundle registration every Registration is done as soon as the application starts meaning at the Application_Start event of Global.asax file like below.