In a project, there may exist multiple CSS and JavaScript files. Bundling is a mechanism or concept of combining multiple JavaScript or CSS files into a 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 as follows:
Now, run the application and press Ctrl+Shift+I to open the Chrome Developer tools, go to the 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 a single GET request, there are multiple GET requests; actually, six requests are going to the server, one for HTML (view) and three for CSS files, and two for JavaScript files. 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 to this issue is combining all CSS files into a single Style bundle and requesting it as a single request, and similarly combining all JavaScript files into a single Script bundle and requesting it as a single request. This process is termed as bundling.
Minification
Minification reduces the size of JavaScript and CSS files by removing comments, blank spaces, etc. For example, consider the CSS file below:
/*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 look like below:
.myclass{background-color:red;height:100px;width:300px;margin-bottom:5px;border:1px solid #000}
You can see that whitespaces and comments are removed, and the codes of multiple lines have been changed to single lines, 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 files into Script bundle and add them to the bundle collection like below:
Bundling - Step 2. Go to Global.asax and add the 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 the 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 the Global.asax file, like below: