Bundling and Minification in ASP.NET Web Forms Application

ASP.NET has in-built for bundling of multiple resources such as js or css files into one file and then minifiy the files to reduce the number of calls made to the server and total data size downloaded from the server thus reducing the total download time and enhanding application’s performance.  In order to use this in web forms application which target version .NET 4.5 and higher, following steps are required

1. Go to NuGet Package Manager and install Microsoft.AspNet.Web.Optimization and Microsoft.AspNet.Web.Optimization.WebForms packages

2. Check web.config to make sure “webopt” tag prefix is added (once you install Microsoft.AspNet.Web.Optimization.WebForms)

<pages>
  <namespaces>
    <add namespace="System.Web.Optimization" />
  </namespaces>
  <controls>
    <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
  </controls>
</pages>

3. Add a class file as following and define the resources you want to bundle

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        Bundle cs = new Bundle("~/bundles/cssv1", new CssMinify());
        cs.Include("~/Resources/css/bootstrap.min.css",
            "~/Resources/css/app.css");
        bundles.Add(cs);

        bundles.Add(new ScriptBundle("~/bundles/jsv1").Include(
            "~/Resources/js/jquery.min.js", 
            "~/Resources/js/bootstrap.min.js"));

        BundleTable.EnableOptimizations = true;
    }
}

4. Go to Global.asax file and register the bundles

protected void Application_Start(object sender, EventArgs e)
{
    try
    {
        RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
    catch (Exception ex)
    {
        // Log Exception here
    }
}

5. In order to use these bundles simply use the statements as following

CSS bundle

<asp:PlaceHolder ID="PlaceHolder1" runat="server">
    <webopt:BundleReference ID="Br1" runat="server" Path="~/bundles/cssv1" />
</asp:PlaceHolder>

JS bundle

<asp:PlaceHolder ID="PlaceHolder1" runat="server">
    <%: Scripts.Render("~/bundles/jsv1") %>
</asp:PlaceHolder>

Read more about this @

Bundling and Minification

Adding Bundling and Minification to Web Forms


Leave A Comment

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