Bundling and Minification

Bundling and minification techniques were introduced in MVC 4 to improve request load time. Bundling allows us to load the bunch of static files from the server in a single HTTP request.

The following figure illustrates the bundling technique:

Loading script files in separate requests

In the above figure, the browser sends two separate requests to load two different JavaScript file MyJavaScriptFile-1.js and MyJavaScriptFile-2.js.

The bundling technique in ASP.NET MVC allows us to load more than one JavaScript file, MyJavaScriptFile-1.js and MyJavaScriptFile-2.js in one request, as shown below.

Bundling and minification

Minification

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

For example, consider the following JavaScript function.

Example: JavaScript
sayHello = function(name){
    //this is comment
    var msg = "Hello" + name;
    alert(msg);
}

Minification will remove the unnecessary white spaces, comments, and shortening variable names to reduce the characters, which will reduce the size of the JavaScript file. The above JavaScript will be minimized as the following script.

Example: Minified JavaScript
sayHello=function(n){var t="Hello"+n;alert(t)}

Bundling and minification impact on the loading time of the page.

Bundle Types

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.

Learn about ScriptBundle in the next section.

Want to check how much you know ASP.NET MVC?