Wednesday, November 25, 2015

Using CDN (Content Delivery Networks) with ASP.NET MVC

CDN (Content Delivery Networks) can be a great way to speed up your ASP.NET MVC application for the following reasons:
  • Files are downloaded from the best geographical location
  • CDN networks are trusted and built for high availability and high usage
  • The browser can download files from several servers at the same time.
  • CDN networks can use caching to further improve performance
With ASP.NET MVC  we can specify a CDN to use AND also a fallback url in the event that the CDN is not available for some reason.

In BundleConfig.cs you can specify a CDN (Content Delivery Networks) url and a fallback url (on web app) if the CDN fails for some reason. The failure is determined on the browser side by checking a javascript expression specified by CdnFallbackExpression.

Here is an example of what can be done for the ~/bundles/query that is set by default on a new project.

            // use CDN if it is available.
            // NOTE: Won't show on local machine unless turn debugging off in web.config
            bundles.UseCdn = true;

            var bundle = new ScriptBundle("~/bundles/jquery",
                @"//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js");
            bundle.CdnFallbackExpression = "window.jquery";
            bundle.Include("~/Scripts/jquery-{version}.js");
            bundles.Add(bundle);

 
Be sure to set the bundles.UseCdn = true. Also, if you are running your project under debug (set in the web.config) then you won't get the bunding, minimizing, optimizations, etc, but you would in production. To force these in development, set debugging to false in the web.config.

Here is a list of CdnFallbackExpression values for common CDNs.

## Library ##      ## Expression ##
jQuery             window.jQuery  
jQuery.UI          window.jQuery.ui  
Modernizr          window.Modernizr  
Bootstrap          $.fn.modal  
jquery.transit     $.transit  
jquery.validate    $.validator  
json2              JSON.stringify  
webfont            WebFont  
jquery.blockUI     $.unblockUI()  
respond            window.respond  
moment             window.moment 
dataTables         $.fn.dataTable

NOTE: List copied from here and the augmented.
Great post on CDN