How to Implement jQuery CDN to Local Failover

A Content Delivery Network (CDN) works by providing alternative server nodes for users to download resources (usually static contents like JavaScript files and images).

For example, if your webpage requires jQuery, instead of loading it from your local web folder, you can load it from a CDN.  By doing so, if your user had already visited a website that makes use of the same version of jQuery from the same CDN, your user would have already cached the jQuery library in his/her browser.  Therefore, the browser will not spend extra time re-downloading the jQuery library which will ensure a faster response time for your webpage to load and execute.

That all sounds good.  However, there is a downside to using a CDN.  Though uncommon, there could be situations where the CDN could be down or inaccessible due to server upgrade, etc.  In this case, if the user does not already have a cached copy of the contents that you require, being unable to retrieve the contents from the CDN can break your website.

To alleviate this problem, we can implement a CDN-to-local failover using JavaScript.

<html>
<head>
<title>jQuery CDN to local failover</title>
</head>
<body>

<!-- Try loading jQuery from CDN first -->
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>

<!-- If CDN fails to load, serve up the local version -->
<script>window.jQuery || document.write('<script src="js/jquery-2.0.3.min.js"></script>');</script>
</body>
</html>

Now we have the best of both worlds.

Leave a Comment