Providing Local JS and CSS Resources for CDN Fallbacks
In a recent podcast the topic of using Content Delivery Networks (CDN) to host common-place resources such as jQuery and Twitter Bootstrap came up. The merits of having access to large scale delivery infrastructures provided by Google and the possibility that the client will already have these asset cached are huge wins. One pessimistic comment which can arise however, is what happens if these CDN’s suddenly become unavailable. Though highly unlikely in the case of Google’s Hosted Libraries, similar acts such development whilst offline may likely result in the same effect. To get around this, hosting fallback local version of the assets is a worthwhile investment. In this post I will go over three different techniques for achieving this by loading an arbitrary example of jQuery, Twitter Bootstrap JS and CSS.
The example implementation below is the simplest example of providing the client with fallback options. Inspired by the HTML5 Boilerplates jQuery fallback example, I have expanded this solution to cater for Twitter Bootstrap.
The second example takes advantage of the great YepNope library, providing us with the ability to test for existence of a predicate and act upon this result. Including YepNope and the provided CSS plugin extension in the document head, we are able to be sure that the ‘complete’ callbacks will only be invoked when either the related JS or CSS assets have been fully loaded.
You will notice that this example is very similar to the basic implementation, testing for the existence of window variables and CSS body properties. However, using this library provides you with the ability to load these assets asynchronously and in parallel (based on the ordering provided). Supplying a sequence of resources to load allows us to be sure that jQuery will be loaded before Bootstrap, which requires this dependency. So as to improve the clients viewing experience a one second timeout has been specified for checking if the bootstrap CSS file has been successfully loaded, before returning the local fallback.
The final example uses the incredibly small library Fallback.js, that was designed for this use-case in mind. This can be seen by how simple the API is to use, with default checking of window variable existence based on the assets key name. Similar to the features provided in YepNope such as loading resources asynchronously we are able to increase page loading times with minimal hassle.
The one issue with this library is that it is tied into checking the window object for resource existence. This does not work well in the case of checking for the successful loading of CSS assets, as we are unable to override the predicate to check for body styling. Though this is a little bit of a pain I still feel that this is the best solution to deploy, even just for the super simple API for loading JS resources.