A short explanation on how to setup script references in bundles to fallback to local copies if serving from a CDN fails.
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,
1 2 3 4 5 6 7 8 9 10 |
@Scripts.Render("~/bundles/jquery") <script type="text/javascript"> if (typeof jQuery == 'undefined') { var e = document.createElement('script'); e.src = '@Url.Content("~/Scripts/jquery-1.7.1.js")'; e.type = 'text/javascript'; document.getElementsByTagName("head")[0].appendChild(e); } </script> |
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,
1 2 3 4 5 6 7 8 9 10 |
bundles.UseCdn = true; var jqueryCdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"; var bundle = new ScriptBundle("~/scripts/jquery", jqueryCdnPath) { CdnFallbackExpression = "window.jquery" }; bundle.Include("~/scripts/jquery-{version}.js"); |
to load jquery from ajax.aspnetcdn.com.
The framework will insert,
1 2 3 4 5 |
<script src=”http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"><\/script> <script> (window.jquery)||document.write( "<script src=”/scripts/jquery"><\/script>") </script> |
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.