CDNs do fail - Set up a fallback with MVC bundling

CDNs do fail - Set up a fallback with MVC bundling

There are many advantages of using public CDN hosted libraries instead of a locally hosted file. But nothing is fail proof, using bundling in MVC4 we can include a fallback in case of CDN failure. Meaning if a third party goes down your site doesn't suffer.

I should be using a CDN?

The advantages of CDNs (content delivery networks) are well documented, so I won't go into too much detail. In short they can speed up your site by providing hosted files in many locations, on many servers. This means the CDN will provide the file closest to the location of the user, resulting in a shorter latency.

Setting up a bundle to target a CDN

MVC4 introduced bundling and minification, allowing you to reduce the file size and number of requests to the server, thus improving performance. We can bundle and minify local CSS and JavaScript files, and also with files that are not hosted locally, such as a CDN.

The following code creates a jQuery bundle using the Google CDN and the local file.

bundles.UseCdn = true;

var jquery =
            new ScriptBundle("~/bundles/jquery", 
            "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js")
                .Include("~/Scripts/jquery-1.10.2.js");

bundles.Add(jquery);

We do two things here. First we enable bundling to use CDNs. Then we register our jQuery bundle, including the URL to the CDN and the locally hosted version. When in debug mode the local version will be used, in release the CDN.

To set up a fallback should the CDN fail, we need to specify a CdnFallbackExpression.

bundles.UseCdn = true;

var jquery =
            new ScriptBundle("~/bundles/jquery", "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js")
                .Include("~/Scripts/jquery-1.9.0.js");

jquery.CdnFallbackExpression = "window.jQuery";

bundles.Add(jquery); 

This is the expression to check if the CDN has failed, in our case, check if the jQuery property exists. If you view the source of your web page, you can see the fallback code.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>(window.jQuery)||document.write('<script src="/bundles/jquery"><\/script>');</script>

Whilst CDNs are great and work 99% of time, there will be occasions when they fail. Make sure your site is robust enough to cope.