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(

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

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

<!DOCTYPE html>
<html xmlns="">
<head runat="server">
        <asp:PlaceHolder ID="PlhBundleStyles" runat="server">
        <%: Styles.Render("~/bundles/styles") %>
    <form id="form1" runat="server">
    <asp:PlaceHolder ID="PlhBundleScripts" runat="server">
        <%: Scripts.Render("~/bundles/scripts") %>

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

      <add namespace="System.Web.Optimization" />

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.