Wednesday, April 22, 2015

ASP.NET MVC - Using CDNs (Content Delivery Network)

By utilizing content delivery networks (CDN)s, you will potentially receive several benefits including improved performance, gains from using different domains, pre-cached files, high-capacity infrastructure and distributed data centers. A CDN can distribute the load, save bandwidth, and boost performance. As individual users request static resources such as javascript and stylesheets, browsers limit the number of concurrent connections (or file downloads) to a single domain at a given time, thus allowing users to download additional requests. Additionally, many CDNs provide localized data centers which are closer to the user, and faster to download. For example, if you are browsing your application's site in San Francisco and need to download the javascript or stylesheets, assuming the CDN has a datacenter in California, it would utilize that location to download the file opposed to making the round trip to your local servers (e.g. could be hosted across the country). In terms of pre-caching, if the CDN has been used on a previous site, it is likely the browser used by the individual won't need to re-download the files again.

Approach

In the Bundle Registration (BundleConfig), you will need to enable the use of CDNs. This can be performed by adding the following property on the BundleCollection, at the beginning of the RegisterBundles method. For simplicity, you can set this value to true, but could potentially drive this from the web configuration files.

// Location: BundleConfig.cs
public static void RegisterBundles(BundleCollection bundles)
{
     // Enable CDN Support
     bundles.UseCdn = true;
     ...
}
Once completed, you will need to add the respective CDNs and their local environment fallbacks, within the RegisterBundles method. You should add CDNs for all of the frameworks that have sustainable CDNs, such as jQuery, Bootstrap, Foundation, Kendo, etc. You could host your local files on an internal CDN to your organization, but it would depend on if there is available and hosted infrastructure.

// Location: BundleConfig.cs
public static void RegisterBundles(BundleCollection bundles)
{
     // Enable CDN Support
     bundles.UseCdn = true;
     ...

     // jQuery Bundles
     const string JqueryCdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.0.min.js";
     bundles.Add(new ScriptBundle("~/bundles/jquery", JqueryCdnPath)
          .Include("~/Scripts/jquery/jquery-{version}.js"));
     ...
     
     // Cache Busting / Optimizations Enabled
     BundleTable.EnableOptimizations = true;
}
With the respective additions of the CDNs, you may need to separate some current bundles, and add to the main layout appropriately.
Post a Comment