Quicktip: Use CDNs for Javascript, but fall back your own copy.

CDNs are fast and all-around fantastic ways to get your sites assets served up, especially for common packages like jQuery and AngularJs.

Except when the CND goes down — and they do go down. Then, you’re stuck with your site not working, and very little you can do to fix it.

But don’t despair! You can still have the awesome power of the CDN when it’s up, and the relative stability of your own copy when it’s not.

Here’s how we do it at Udacity. Just picking on jQuery and Angular here, but the general pattern holds for any javascript library/file you wish to apply it to.

A couple things to note:

  1. The blocking nature of loading external javascript means that we don’t have to worry about our fallbacks firing off before our library either loads or fails to load.
  2. We use the escaped %3C and %3E versions of < and > when we’re writing our script tag out because, even in a string literal, you can’t have </script> as that would prematurely end the execution of your script tag. You could write out <\/script>, but the %3C version will also parse in XHTML, if you’re down with that. Figured I’d go generic here as the fully escaped version will work everywhere.

There ya have it. You’ll load jQuery and Angular from their CDNs in all their glory, but in case those CDNs are down, you’ll fall back to your own copy of the libraries.

Bonus: I do a lot of work from the road, and if you ever have to do the same, having local fallbacks means that when the connection inevitably drops out, you’re still good to go.

Leave a Reply

Your email address will not be published. Required fields are marked *