Open In App

MVC Framework Bundling

Last Updated : 07 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Bundling is a feature of the MVC framework in the .NET Framework that allows developers to combine multiple CSS and JavaScript files into a single file. This can help improve the performance of web applications, as it reduces the number of requests required to load the page.

The bundling feature works by creating a bundle object, which is a logical group of one or more CSS or JavaScript files. The bundle object specifies the files to include in the bundle, as well as any options for minification, caching, and other settings.

When the application is run, the bundling feature automatically combines the files in each bundle into a single file, and serves the file to the client. This helps reduce the number of HTTP requests required to load the page, and can improve the performance of the application.

Some of the key features of bundling in the MVC framework include:

  1. Minification: The bundling feature includes support for minification, which is a process that removes unnecessary characters from CSS and JavaScript files to reduce their size. This can help improve the performance of the application by reducing the amount of data that needs to be transferred over the network.
  2. Caching: Bundling includes support for caching, which allows the client’s browser to store a copy of the bundled file locally. This can help improve the performance of the application by reducing the number of HTTP requests required to load the page.
  3. Customization: Developers can customize the bundling feature by creating their own bundles and specifying their own options for minification, caching, and other settings. This allows developers to fine-tune the performance of their application based on their specific needs.

Overall, the bundling feature in the MVC framework is a powerful tool for improving the performance of web applications. By reducing the number of HTTP requests required to load the page, bundling can help improve the user experience and make the application more responsive and efficient.

The MVC provides us the two features to reduce the number of requests to access the resource file on the server i.e. Bundling and Minification.

Bundling is one of the features of MVC. By implementing this, we can improve performance request load time. Minification is the process of removing unnecessary data without changing its functionality such as removing white spaces, comments, converting the large variable names to small, etc. It makes the file smaller so that it will take less time to load it.

The System.Web.Optimization namespace provides the bundling approach in ASP.NET MVC which is present in Microsoft.Web.Optimization assembly. 

To implement bundling in the application, you have to add this DLL as a reference in your project using System.Web.Optimization.

Bundling’s aim is to, Improve the performance response and request load time of web pages”.

The bundle is nothing but encapsulating the files in one unit. Suppose our application contains multiple CSS files like bootstrap and others so all that files we can bind in one unit.

Let’s see on the code end. In an ASP.NET MVC Web Application, while creating a project if you select the MVC template then it auto-generated configuration of bundle files.

After Project create, You can check under,

  • App_start folder: You’ll find BundleConfig file in which all script and style bundles are defined.
  • web.config file: You’ll see the debug mode is set to true.

XML




<system.web>
    <compilation debug="true" />
</system.web>


Note that compilation debug mode is set to true right now. This means that, when this application runs, the compiler will bundle or minify our JavaScript and CSS files. If not set to true, it will not bundle the files. or

You can override this Web.config setting with the EnableOptimizations property on the BundleTable class in Global.asax file Such as

C#




public static void RegisterBundles(BundleCollection bundles) {
    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                 "~/Scripts/jquery-{version}.js"));
 
    // This line of code enable bundling
    BundleTable.EnableOptimizations = true;
}


  • In reference, you’ll find optimization NuGet package
    Assembly System.Web.Optimization
  • Global.asax: You’ll find bundle register
    BundleConfig.RegisterBundles(BundleTable.Bundles);

Create Bundle:

C#




using System.Web.Optimization;
 
namespace Bundle_MVC {
public class BundleConfig {
    
    public static void
    RegisterBundles(BundleCollection bundles)
    {
        //Script bundles
        bundles.Add(
            new ScriptBundle("~/bundles/jquery")
                .Include("~/Scripts/jquery-{version}.js"));
 
        bundles.Add(
            new ScriptBundle("~/bundles/jqueryval")
                .Include("~/Scripts/jquery.validate*"));
 
       
        bundles.Add(new ScriptBundle("~/bundles/modernizr")
                        .Include("~/Scripts/modernizr-*"));
 
        bundles.Add(new ScriptBundle("~/bundles/bootstrap")
                        .Include("~/Scripts/bootstrap.js"));
       
        
        //Style Bundles
        bundles.Add(new StyleBundle("~/Content/css")
                        .Include("~/Content/bootstrap.css",
                                 "~/Content/site.css"));
    }
}
}


As you can see,

  • This file contains only one method i.e. RegisterBundles(). In this method, we have to register all files that must be loaded with one request. Here examine the RegisterBundles method which is used to create, register and configure bundles. You can see ScriptBundle and StyleBundle objects we are using for bundling the js and CSS types of files.
    • ScriptBundle: is responsible for Script files i.e javascript (JS).
    • StyleBundle: is responsible for stylesheet files i.e CSS.
  • The code in RegisterBundles method creates new JavaScript and CSS bundles named such as ~/bundles/jquery ,~/bundles/modernizr,~/Content/css like so on those includes all the appropriate (that is debugging or minified) files in the Scripts and Style folder.

Let’s see a little deeper the first Scriptbundle i.e.

C#




bundles.Add(
      new ScriptBundle("~/bundles/jquery")
    .Include("~/Scripts/jquery-{version}.js")
);


In this bundle,

  • That match the wild card {version } string “~/Scripts/jquery-{version}.js”. This means, for debug configuration, it will be added the file jquery-1.7.1.js to the bundle and In a release configuration, jquery-1.7.1.min.js will be added.

Note: This wildcard pattern { version } is used to automatically create that particular type of script bundle with the appropriate version in the Scripts folder. It automatically selects the full version for debug configurations and the “.min” version for release builds.

Also, you can see in the code

  • .Include() method: The include method takes an array of strings, where each string is a virtual path to the resource.
  • Instead of this method, we can use IncludeDirectory to include all files from folder to bundle (based on a search pattern). We can include a subfolder as well in this method.

Let’s see how to define IncludeDirectory:

C#




Bundle.Add(new ScriptBundle("~/bundle/js")
         .IncludeDirectory("~/Content/JS","*.js"));
         // .IncludeDirectory("~/Content/JS","*.js",true));
 
bundles.Add(new StyleBundle("~/bundle/css")
         .IncludeDirectory("~/Content/themes", "*.css"));
        // .IncludeDirectory("~/Content/themes", "*.css",true));


Here,

  • ~/bundle/js  and ~/bundle/css : name of bundle
  • ~/Content/JS and ~/Content/themes : path of folder
  • *.js  and *.css :  search pattern

There is a third parameter, that represents the boolean value for search in subfolders or not. If want then set to true.

Register Bundle: After bundling, we need to register the bundle global.asax file. So we call this method in the Application_start method and register the bundle to bundle Config.

C#




using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
 
namespace Bundle_MVC {
public class MvcApplication : System.Web.HttpApplication {
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(
            GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}
}


Render Bundle: After registering, render the bundles on view, you can see the script and style bundles in the view folder layout file.

  • JS: @Scripts.Render(“Specify_scriptname”) : Used to Render javascript type of bundles
  • CSS: @Styles.Render(“Specify_styletname”) :Used to Render CSS  type of bundles

HTML




<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content=
          "width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
   
    <!--Hidden code inside layout view-->
   
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
</head>
<body></body>
</html>


Output: As we have bundled site and bootstrap CSS files in style bundle name CSS. You can see, in the in-network tab for CSS only one request is present and if you see under the source tab, there is one content folder in which you will see only one file showing instead of separate for site and bootstrap and the same for js files you can see under bundles folder.

And if you open any bundle file, it will show an unreadable type of data as you are seeing in the image below. It is minified data so it is not a human-readable format. You can reformat it to be readable by clicking the { } symbol in the Source tab.

Note: In this way, you can check the performance of these files. With or without bundling, you will see a major difference in performance in the terms of size or time.

Advantages:

  • Bundling helps to download the same type of files using a single request instead of multiple requests.
  • Instead of fetching all resource files ( CSS and js ) one by one we can create a bundle group of resources and fetch that bundle in one single request.
  • Minification helps to reduce the size of the files and improve the responsiveness of the requests.
  • It solves the issue of server change file not being reflected on the browser, bundling takes care of this issue automatically by adding hashcode to each bundle as a query parameter in URL whenever you change the contents of the JS and CSS files, a new hash code will be generated and automatically rendered on the page.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads