Monday, April 21, 2014

Bootstrap 3 HTML Template with CDN Failover for JS and CSS

I wanted to create a nice, simple template for Bootstrap 3.0 that uses a failover technique I learned about at a recent ASP.NET user group meeting (Thanks Alek Davis).

The Getting Started section of shows a CDN example, but the HTML template that assumes you have local Bootstrap JS and CSS files.  I found lots of examples of Javascript failover techniques, most notably Scott Hanselman’s CDNs fail, but your scripts don’t have to… blog post. A little more Googling turned up this technique to see if Bootstrap loaded properly. I adapted the code from github to the shorthand code from Scott’s blog to create this nice Bootstrap 3 HTML template that attempts to load JQuery and the Bootstrap 3 JS and CSS files from CDN. Should any fail, it loads the files locally.

Note: This template is expecting the following local resources:

May not be IE compatible!

 <!DOCTYPE html>  
 <html lang="en">  
   <meta charset="utf-8">  
   <meta http-equiv="X-UA-Compatible" content="IE=edge">  
   <meta name="viewport" content="width=device-width, initial-scale=1">  
   <title>Bootstrap 101 Template</title>  
   <!-- Latest compiled and minified Bootstrap 3 CSS CDN-->  
   <link rel="stylesheet" href="//">  
   <h1>Hello, world!</h1>  
   <!-- jQuery (necessary for Bootstrap's JavaScript plugins) CDN Failover -->  
   <script src="//"></script>  
   <script>window.jQuery || document.write('<script src="js/jquery-1.11.0.min.js">\x3C/script>');</script>   
   <!-- Include all compiled plugins (below), or include individual files as needed -->  
   <!-- Latest compiled and minified JavaScript CDN Failover-->  
   <script src="//"></script>  
   <script>$.fn.modal || document.write('<script src="js/bootstrap.min.js">\x3C/script>');</script>  
   $(document).ready(function() {  
     //CSS CDN Failover (If you change the body color, you will need to change the rgb value below.)  
     $('body').css("color") == 'rgb(51, 51, 51)' || $("head").prepend("<link rel='stylesheet' href='css/bootstrap.min.css' type='text/css' media='screen'>");  

Scott Hanselman: CDNs fail, but your scripts don't have to - fallback from CDN to local jQuery
GitHub MaxCDN / bootstrap-cdn: Check if Bootstrap is loaded #111
Bootstrap Website:

1 comment: