Brains Coders

Brains Engineering Blog

Bundling and Minification with Asp.Net Web Forms

Bundling and minification are two techniques you can use in ASP.NET 4.5 to improve request load time.  Bundling and minification improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.)


First of all we need to check if we have the folowing packages:

  <package id="Microsoft.AspNet.Web.Optimization" version="1.0.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.Web.Optimization.WebForms" version="1.0.0" targetFramework="net45" />

if not, open the NuGet package manager and install them.


Then create, if it's not already there, the folder "App_Start", and create inside it the class BundleConfig.

In this class let's create the method to register bundles, both scripts and styles, by creating a new bundle and including files in it:


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/themes/base/css").Include(
   "~/Content/themes/base/jquery.ui.core.css",
   "~/Content/themes/base/jquery.ui.resizable.css"));
}


The above method must be called in the Application_Start method of Global.asax

        protected void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }


Now we are able to include the bundles in our web pages by using the following code:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
        <asp:PlaceHolder ID="PlhBundleStyles" runat="server">
        <%: Styles.Render("~/bundles/styles") %>
    </asp:PlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    <asp:PlaceHolder ID="PlhBundleScripts" runat="server">
        <%: Scripts.Render("~/bundles/scripts") %>
    </asp:PlaceHolder>
    </form>
</body>
</html>


Don't forget to add, if not already automatically added, the optimization namespace in the web.config:

<system.web>
  <pages>
    <namespaces>
      <add namespace="System.Web.Optimization" />
    </namespaces>
  </pages>
</system.web>


Remember that bundling and minification are enabled only when you set <compilation debug="false" />, otherwise you will get the single files (not bundled) and not minified, in order to properly debug the web application.






Loading