Using CDN in your MVC Bundling Configurations

There are advantages to referencing resources via a CDN. Bundling can be set up in such a way to use local references when debugging and CDN when in release mode. Here we will see how to set up bundling for jQuery and jQueryUI. If you do not have a local version of the libraries you can install them via NuGet using these commands in the Package Manager Console window.

Install-Package jQuery -Version 1.11.3
Install-Package jQuery.UI.Combined -Version 1.11.4

Here a specific version has been referenced to match the CDN version of the files on googleapis

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

<!-- And the related css file -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">

From these references the BundleConfig will look something like this

using System.Web;
using System.Web.Optimization;

namespace ApplicationNamespace
{
    public class BundleConfig
    {
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.UseCdn = true;

            bundles.Add(new ScriptBundle("~/bundles/jQuery",
                "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js").Include(
                "~/scripts/jquery-{version}.js")); 

            bundles.Add(new ScriptBundle("~/bundles/jQuery",
                "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js").Include(
                "~/scripts/jquery-ui-{version}.js")); 
        }	
    }
}

Notice in the BundleConfig class that the UseCdn property has been set to true, specifying that we want to use the CDN version when it is available otherwise local files will be used. The {version} placeholder is a way of specifying none specific versions of the libraries and will load whatever version is installed in the scripts folder. The last thing to configure is the debug setting in the web config file.

<system.web>
    <compilation debug="true" targetFramework="4.5.1" />
</system.web>

When the compilation debug setting is set to true the local files will be loaded. In the production environment where the compilation debug is set to false or removed altogether the CDN versions will be referenced.