Bundle in ASP.NET MVC

Author - Nipun Negi
30.07.2019
|
0 Comments
||

Bundle in ASP.NET MVC

Bundling is a process that allows us to load a bunch of static files from the server into one HTTP request. We can load multiple CSS and Javascript files using bundles.

Let’s take an example :

In the above example browser sends two separate requests for loading two different JS files.

Bundling allows us to do that in one request.

In MVC 5 bundle classes are included in System.web.Optimization namespace:

Open App_Start\BundleConfig.cs file in the MVC folders. The BundleConfig.cs file is created by MVC framework by default. You should write your all bundling code in the BundleConfig.RegisterBundles() method.

Minification

Minification optimizes script or CSS file size by removing unnecessary comments and white space and shortening variable names to one character.

Example: JavaScript

check = function(name){
 //it is comment
 var msg = "Check" + age; 
alert(msg);
 }

The above JavaScript will be optimized and minimized into the following script.

check =function(n){var t="Check"+n;alert(t)}

Minification removes unnecessary white space, comments and also shortening variable names to reduce the characters which in turn will reduce the size of the JavaScript file.

Bundling and minification impacts the loading of the page, it loads the page faster by minimizing the size of the file and number of requests.

Bundle Types

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

public static void RegisterBundles(BundleCollection bundles) { 
// create an object of ScriptBundle and
 // specify name of bundle (as virtual path) as constructor parameter 
ScriptBundle scB = new ScriptBundle("~/bundles/bootstrap");
 //use Include() method to add all the script files along with their paths 
scB.Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js" ); 
//Add it bundle into BundleCollection 
bundles.Add(scB);
BundleTable.EnableOptimizations = true; 
}

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

 
public static void RegisterBundles(BundleCollection bundles) { 
bundles.Add(new StyleBundle("~/bundles/css").Include( "~/Content/bootstrap.css",          
                                                                                         "~/Content/site.css" )); 

 }

Include the bundles in razor view

For StyleBundle:
@Styles.Render(“~/bundles/css”)

For ScriptBundle:
@Script.Render(“~/bundles/bootstrap”)

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *