MVC Bundling

The amount of style sheets and JavaScript files included with a website these days is staggering. As you develop solutions, it is becoming important to be aware of the amount of different style sheets and JavaScript files you are forcing the user to download on each request. A simple way of limiting the amount of these requests, while keeping your code separated in a logical way, is to implement bundling in your MVC Project.

If you have 12 different CSS files and 8 different JavaScript files in your solution, it’s easy to combine these into two different requests. In your App_Start folder, create a new class called BundleConfig. Within the class, create a public static void method called RegisterBundles() which will accept a BundleCollection object as a parameter. You then will add a ScriptBundle collection, and a StyleBundle collection to the BundleCollection.

See example below.

Now, in your Application_Start() method within the Global.asax file, you call your bundling provider. A good idea is to enable optimizations only when building in release mode. When optimizations are enabled, the bundle will automatically combine each ScriptBundle and StyleBundle into one request, as well as minify each result.

The last step is to modify your _layout.cshtml file to reference the bundles. In the BundleConfig file that we created, we created a name for each of the ScriptBundle and StyleBundles. You reference these in your layout using the following format.

That’s it! You have now optimized your website, limiting the amount of requests done per page per user while allowing separation of your style sheets and scripts during development.

We hope you have found this edition of “To The Point” by Kevin Doig to be helpful and informative. Look out for our next installment as we continue to explore unique topics from business to the latest technology.

We want to hear your point! If you have any ideas, suggestions or any questions about our weekly blog, please contact us at:

Warm regards,

Point Alliance Team