Using Google-Hosted jQuery With a Local Fallback

Referencing commonly-used JavaScript libraries, like jQuery, stored on Google’s CDN is a good way to speed up your site. Many popular websites do so, which means the chances of a user having jQuery sitting in their browser cache already is pretty high. It doesn’t make a whole lot of sense to download it all over again for another website, does it? Using the copy on the Google Libraries CDN just makes a lot of sense.

But what if the servers Google has hosting it went down for some reason? Given Google’s track record, it’s not likely to be an issue, but it’s a good point. Fortunately, you can easily reference a backup. You can have a copy of jQuery on your server, and use a little bit of JavaScript to load it only if the Google one doesn’t load for some reason.

This little snippet, found in HTML5 Boilerplate, will do just that:

<script src="//"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.6.4.min.js"><\/script>')</script>

This should even work with WordPress, if you put the second script line right before the </head> tag in your theme.

  • Reuben Chovuchovu

    Thanks I was actually looking for this helpful solution.