MVC script fallback for CDNs

A short explanation on how to setup script references in bundles to fallback to local copies if serving from a CDN fails.

Back to blog

The ASP.NET Web Optimization from 20th October includes new functionality for serving files from your own web server in the the (unlikely) situation where serving from a CDN fails.

Previously, you had to explicitly write a bit of javascript to inject a script header into the DOM if the file had not been loaded correctly from the CDN.  Something like,

Gets messy the more files you serve from the CDN.

In the latest release, the Bundle class includes the property CdnFallbackExpression.

If you render a bundle that uses a CDN with the CndFallbackExpression specified, the framework renders a bit of script into the DOM for the fallback check. For example, if you setup your bundle as follows,

to load jquery from ajax.aspnetcdn.com.

The framework will insert,

into the page which falls back to a local bundle if jquery fails to load from the cdn

As you read this far, you should follow me on twitter here.