The benefit of loading libraries like jQuery and Bootstrap from a CDN is that if web developers everywhere load the libraries from the CDN then visitors to the website may already have the library loaded in their cache. Everyone loves a page that loads faster, but what if the CDN is down temporarily for maintenance? These code snippets can help you detect if the CDN version was loaded, and if not load a local copy of the JS or CSS file instead.

Loading CDN JavaScript Files with Fallback to Local Files

To load both jQuery and jQuery UI from CDN with automatic fallback to a local copy, you can use the following code snippet:

If you haven’t seen it before, by omitting the “http:” before the src attribute we our document will be loaded using whichever protocol is currently in use (http or https). If your use case differs you can just specify one protocol or the other instead.

Loading CDN Stylesheets with Fallback to Local Files

To load the Twitter Bootstrap or other stylesheet files from a CDN, with automatic fallback to a local copy, use the following code:

Other Examples

For the Twitter Bootstrap framework:

And for TinyMCE:

Resources