Saturday, August 24, 2013

Bundling and Minification in MVC 4

What is Bundling and Minification?

  • Bundling and Minification  are the new features in ASP.NET MVC 4.
  • Bundling and Minification are two techniques that improves the first request load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.)
  • In Simple terms, Bundling helps you to download files of same type using one request instead of multiple requests. This way you can download styles and scripts using less requests than it takes to request all files separately.
  • Minification performs a variety of different code optimizations to scripts or css, such as removing unnecessary white space,comments and shortening variable names to one character. 

How to implement Bundling ?

In ASP.NET MVC 4 web application you can find BundleConfig.cs file under App_Start folder. This file contains BundleConfig class that has only one method RegisterBundles() which is used to create, register and configure bundles. In this method files that must be downloaded with one request are added to bundles.

public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

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

            bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));

            bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
                        "~/Content/themes/base/jquery.ui.core.css",
                   "~/Content/themes/base/jquery.ui.theme.css"));
        }
    }

The {version} wild card matching shown above is used to automatically create a jQuery bundle with the appropriate  version of jQuery in your Scripts folder.  In this example, using a wild card provides the following benefits:
  • Special placeholder {version} in file name means that file name may contain version number. This name pattern is specially good for jQuery that is updated often. When you replace your old jQuery file that has version number in its name with newer version then you don’t have to rename the file.  It is enough when file has different version number in its name.
  • Automatically selects the full version for debug configurations and the ".min" version for release builds.
In the Global.asax file, the Bundles are added :

Global.asax.cs :

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

Bundles are referenced in views using the Render method, ( Styles.Render for CSS and Scripts.Render for JavaScript). The following markup from the Views\Shared\_Layout.cshtml file shows how the default ASP.NET project views reference CSS and JavaScript bundles.

<!DOCTYPE html>
<html lang="en">
<head>
    @Styles.Render("~/Content/themes/base/css", "~/Content/css")
</head>
<body>
   @Scripts.Render("~/bundles/jquery")
</body>
</html>

ScriptBundle and StyleBundle :

If you noticed then script bundle and style bundle have different classes. ScriptBundleis targeted to scripts and you shouldn't add any other files to script bundles. Same with styles goes for StyleBundle. Both of these classes extend general Bundle class that offers bundling functionality.

How to Create Custom Bundles :

Bundle class from Microsoft.Web.Optimization is used to create Custom Bundles. To create custom bundle we need to create object of Bundle class by specifying virtual path through which we can reference custom bundle and transform type whether it is JavaScript or CSS. 

Below are the two custom bundles in
Application_Start event

Bundle indexBundle = new Bundle("~/IndexBundle", typeof(JsMinify));
indexBundle.AddFile("~/Scripts/Demo JS Files/JS-File-1.js");
indexBundle.AddFile("~/Scripts/Demo JS Files/JS-File-2.js");
BundleTable.Bundles.Add(indexBundle);
 
Bundle createBundle = new Bundle("~/CreateBundle", typeof(JsMinify));
createBundle.AddFile("~/Scripts/Demo JS Files/JS-File-3.js");
createBundle.AddFile("~/Scripts/Demo JS Files/JS-File-4.js");
BundleTable.Bundles.Add(createBundle);

Advantages of Bundling:

Bundling and Minification primarily improve the first page request load time. Once a webpage has been requested, the browser caches the assets (JavaScript, CSS and images).  So bundling and minification won’t provide any performance boost when requesting the same page, or pages on 
the same site requesting the same assets.

Debug mode for Bundling:

In debug-mode bundling is switched off by default. To force bundling in debug-mode 
add the following line in the beginning of RegisterBundles():
BundleTable.EnableOptimizations= true;

Bundles Caching:

Bundles set the HTTP Expires Header one year from when the bundle is  created.

2 comments:

  1. Most Frequently asked MVC Interview Questions and Answers specially For 2 Years Experienced are here, All the best by mytectra
    mvc interview questions

    ReplyDelete
  2. I have a question. What if we have two javascript files with same function name. How bundling concept handle this. Which function it calls first. Can you please explain.

    ReplyDelete