How I applied Bundling in my application

While trying to optimize my old asp.net application, I found that lot of java script files and css files are affecting the performance of my web applications.To optimize the performance of an application I found that bundling and minification can significantly improve the performance. It can be applied on MVC as well as in ASP.NET web forms. So I decided to take a hand on this. Before applying bundling and minification, it is good to understand the basic logic behind this.

Below links were very helpful for me:

1 :http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification
2 :http://msdn.microsoft.com/en-us/magazine/dn451436.aspx


What is bundling?

In Asp.NET bundling is a process of wrapping up all included file as a single downloadable resources so that browser’s call for resources get minimized. Instead of making one to one call to each file, browser gets all bundled file in a single call.

What is minification?
Minification is the process of removal of all unnecessary characters like extra spaces, comments, new line etc, which has been added for readability, from files to reduce the size of files so that the data transfer can be minimized.

Lets understand it by example. Suppose we have a function for sum


function sum(a,b)
{
return (a + b); //will return the sum of numbers
}

Generally when we write this function in a file, the whole js file is downloaded as it is. But with minified js file above code will look like :

function sum(a,b){return (a+b);}

Clearly, it reduces the size of file :).

How Bundling works when any file get updated?
Whenever any included file of the bundle is updated, a new token is created for bundle query string parameter which force to download full updated bundle next time when a client request for a page bundle having references.

When to apply bundling?
a: Having many common js/css files used in through out the application
b: To much js/css files in use in page

Bundles should be created per usability in the pages where we actually need them. For example applications common css file can be added in a single bundle, all common js files can be added in a single bundle even we can create page specific bundles.

Where we can Apply this :
With Asp.Net we can apply it on MVC as well as Asp.Net forms or anywhere we are handling js/css

Steps to apply bundling: Below are the steps to apply bundling:

Step 1: Add nuget package “Microsoft ASP.NET Web Optimization Framework”

We can see, adding this nuget package adds few lines in our web.config files too:

<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
</assemblyBinding>
</runtime>

Step 2: Add BundleConfig.cs in App_Start folder. If folder does not exists please add it first.

Open BundleConfig.cs and add “System.Web.Optimization namespace” in using section. Code of BundleConfig.cs will looklike below:

using System.Web.Optimization;

namespace medAppz2.App_Start
{
public class BundleConfig
{
public static void RegisterBundle(BundleCollection bundle)
{
//bundle all common js files, required in every page
bundle.Add(new ScriptBundle("~/bundles/MyAppStartupJs")
.Include("~/include/js/General.js",
"~/include/js/Validation.js",
"~/include/js/NormalAbnormalCheck.js"));

//wrapup all css in a bundle
bundle.Add(new StyleBundle("~/bundles/MyAppStartupCss")
.Include("~/include/style/main.css",
"~/include/Style/Container.css",
"~/include/Style/BasicElement.css"));

BundleTable.EnableOptimizations = true;
}
}
}

See, there is a static method RegisterBundle which takes BundleCollection as a parameter.
Then bundle.Add() methods has been used for creating ScriptBundle & StyleBundle. You can add n numbers of bundles according to requirements. You can see, I have added four js file in a single bundle.

With above code I have created two bundles: MyAppStartupJs and MyAppStartupCss. We will use these two in next steps.

There is one more line to enabled bundling and minification of bundle references:
BundleTable.EnableOptimizations = true;.

Setp 3: Now need to register the bundle in Application_Start event of Global.asax.cs file

protected void Application_Start(Object sender, EventArgs e)
{
BundleConfig.RegisterBundle(BundleTable.Bundles);
}

Step4 : Now all settings are done, Just need to add bundle references in aspx files
Setp4.1 : Add below line in your page. It will allow use to use Styles.Render, Scripts.Render method in aspx page.
<%@ Import Namespace= “System.Web.Optimization” %>

Note : With MVC we don’t need to use above line.

Step4.2 : To render these files just need to write below lines in your head tag. Of course, you can also add js bundles after the body tag / other places for better performance 🙂 )

<% Styles.Render("~/bundles//MyAppStartupCss")%>
<% Scripts.Render("~/bundles//MyAppStartupJs")%>

We are done :). Now while calling a page request, if we look at network exchanges in browser, we can find that now there is only a single call per bundle for js and one single call per bundle css.

If we check the page view source, in head section, there will be link for bundles like :

<link href="/BundlingAndminificationDemo/bundles/MyAppStartupCss" rel="stylesheet"/>
<script src="/BundlingAndminificationDemo/bundles/MyAppStartupJs"></script>

Same we can verify with browser using f12-> Network section, which shows details of bundle like size, type, download time etc and confirms a reduces size file.

We can implement bundling in same way with MVC too. Here will have to render the bundles in views(razor/aspx etc)

Point of consideration : As bundling works on Application_Start, Always application start will be needed after modifying any included resource of bundle otherwise the new changes will not be reflected on the page as it will still be pointing to the older bundle.

Happy Coding

Written By : Vinod Pandey, Sr. Software Engineer, Mindfire Solutions

Advertisements

Posted on September 24, 2014, in ASP.Net, Javascript and tagged , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: