CdnFallbackExpression for JQuery, JQuery.UI, Modernizr and Bootstrap

So, like a total chump, I didn’t really understand what the CdnFallbackExpression on a Bundle actually meant. It didn’t help that pretty much every example you find online shows you what to write for jQuery, but nothing else.

With Tournr, I want to use CDN’s where I can for obvious reasons – and so I dutifully tried the jQuery example:

var bundle = new Bundle("~/Scripts/jQuery").Includes("~/Scripts/jQuery-2.1.1.js");
bundle.CdnFallbackExpression = "window.jQuery";
bundle.CdnPath = "https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.1.min.js";
bundles.Add(bundle);

Works just fine.

And this is the point things start to go awry. In my naivety I didn’t really understand what was happening. I didn’t twig that the CdnFallbackExpression has to be window.jQuery. It won’t work otherwise. Being a developer, I took it upon myself to wrap up the above into a method, something like:

private static Bundle GetBundle(string name, string cdnPath, params string[] includes){ /**/ }

Being snazzy and using the ‘name’ as a fallback expression.

That’s right, the name, (actually “window.{0}” where {0} was the name), which as you can imagine worked great for jQuery, not so for anything else. I believed that what I wanted was something like:

<script>(window.bootstrap) || document.write('<script src="~/Scripts/bootstrap.min.js><\/script>')</script>

I imagine you looking at this, perhaps with your palm attached to your forehead. You are right to do so.

So, I test tournr, hmmm bootstrap is no longer working. If I remove the CDN stuff, it’s all good, so I guess bundling must be b0rked?? I spent ages looking for errors in the Console windows of IE and Chrome Developer Tools – nada. Network was showing the files downloading, but curiously I noticed 2 copies downloading, so my local and my CDN loading. Odd. One or the other please, not both. This led to my eureka moment!

The CdnFallbackExpression has to be set CORRECTLY. No amount of time saving auto setting was gonna save me, so now the GetBundle  looks more like this:

private static Bundle GetBundle(string name, string cdnPath, string fallbackExpression, params string[] includes){ /**/ }

So, the fallback expressions for jQuery, UI, etc are listed below:

Library

Expression

jQuery window.jQuery
jQuery.UI window.jQuery.ui
Modernizr window.Modernizr
Bootstrap $.fn.modal

Print | posted @ Friday, July 4, 2014 11:25 AM

Comments on this entry:

No comments posted yet.

Post A Comment
Title:
Name:
Email:
Comment:
Verification: