Using CDN Bundle Config in ASP.NET MVC

This article explains how to use CDN in MVC script bundles.

Bundling is a technique used in ASP.NET 4.5 to improve request load time. This technique improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript).

If you are using libraries like JQuery, AngularJS in your application, instead of loading them from your own server you can use the CDN url of these libraries. So, when you run your application in production environment these files will be loaded from CDN itself. If the CDN is not available then these files will be loaded from your server.

How to add CDN in MVC bundles:


First of all enable cdn feature (by default it is set to false).

bundles.UseCdn = true;

 Then add your library (JQuery or AngularJS or any other) bundle from CDN. In my example am using JQuery library

var jqueryBundle = new ScriptBundle("~/bundles/jquery", "http://code.jquery.com/jquery-2.0.3.min.js").Include(
                "~/Scripts/jquery-{version}.js");
            jqueryBundle.CdnFallbackExpression = "window.jquery";
            bundles.Add(jqueryBundle);

Use of CdnFallbackExpression is when CDN server is unavailable it loads the file from your server.

In this way we can use CDN in MVC script bundles.

Test CDN bundle in Local Evnironment (Debug Mode):


To test this feature locally you have to run your application in debug="false" mode or you cal also use BundleTable.EnableOptimizations = true;

For more posts on MVC visit : Asp.Net MVC

No comments:

Post a comment