Loading jQuery and other libraries from Google’s CDN with local fallback

It is generally preferable to load commonly used  libraries such as jQuery from the Google CDN as it is likely that the client browser will already have a cached copy from that source, thus reducing page load time and bandwidth. Even if there isn’t a cached copy, the library will load faster from Google’s servers than from the website’s server.

The code snippets below attempt to load a minified version of jQuery from Google Hosted Libraries, and if this fails for any reason, will fall back to loading it from the website’s server. Version 2.1.0 is used in this example but the majority of released versions are available on the CDN. Version information can be obtained at https://developers.google.com/speed/libraries/devguide#jquery.

LIBRARIES_URL / libraries_url is the absolute url to your libraries directory including a following slash and is assumed to have been previously defined in PHP in the first example, or as a javascript variable in the second.

PHP:

echo '
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>window.jQuery || document.write(\'<script src="' . LIBRARIES_URL . 'jquery/jquery-2.1.0.min.js">\x3C/script>\')</script>
';

HTML/Javascript:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>window.jQuery || document.write(\'<script src="' + libraries_url + 'jquery/jquery-1.7.2.min.js">\x3C/script>\')</script>

Libraries currently hosted by Google include:

  • AngularJ
  • Dojo
  • Ext Core
  • jQuery
  • jQuery Mobile
  • jQuery UI
  • MooTools
  • Prototype
  • script_aculo_us
  • SWFObject
  • three.js
  • Web Font Loader

More information can be obtained at https://developers.google.com/speed/libraries/devguide.

Leave a Reply

Your email address will not be published. Required fields are marked *