How (and why you should) Include jQuery from Google CDN in WordPress

Including jQuery from Google’s CDN has some advantages. Here are a few:

  • Caching Perhaps the greatest benefit of including google hosted jQuery is that there is a good chance your visitors may not even need to download jQuery. They might have visited some other website using Google hosted jQuery and already have it downloaded and cached by their browsers.

  • Less Latency Google have jQuery distributed across geographically dispersed servers. When a browser resolves the URL for the jQuery file it will automatically get downloaded from the closest available server.

  • Maximized Parallel Downloads By not having jQuery on your own domain it can be downloaded in parallel with other stuff. You can read more on parallel downloads here: Maximizing Parallel Downloads

Include jQuery from Google in your WordPress Theme

If you use WordPress any scripts you want to include should be enqueued to avoid them from being included more than once. Enqueued scripts will then be included by the wp_head or wp_footer function calls.

Here is a function that gets triggered by the wp_enqueue_scripts -action to make a theme use the Google CDN version of jQuery. To use it, just add it to your theme’s functions.php file.

/*
Enques jQuery from Google CDN. 
Uses the currently registred WordPress jQuery version.
*/
function appglobe_jquery_enqueue() { 

   /* 
   Probably not necessary if called with the 'wp_enqueue_scripts' action.
   */
   if (is_admin()) return; 

   global $wp_scripts; 

   /*
   Change  this flag to have the CDN script  
   triggered by wp_footer instead of wp_head.
   If Google CDN is unavailable for some reason the flag 
   will be ignored and the local WordPress 
   jQuery gets enqueued and included in the head
   by the wp_head function.
   */
   $cdn_script_in_footer = false; 
   /*
   Register jQuery from Google CDN.
   */
   if (is_a($wp_scripts, 'WP_Scripts') && isset($wp_scripts->registered['jquery'])) {
      /* 
      The WordPress jQuery version. 
      */
      $registered_jquery_version = $wp_scripts -> registered[jquery] -> ver; 

      if($registered_jquery_version) {
         /* 
         The jQuery Google CDN URL. 
         Makes a check for HTTP on top of SSL/TLS (HTTPS) 
         to make sure the URL is correct.
         */
         $google_jquery_url = ($_SERVER['SERVER_PORT'] == 443 ? "https" : "http") . 
         "://ajax.googleapis.com/ajax/libs/jquery/$registered_jquery_version/jquery.min.js";

         /* 
         Get the HTTP header response for the this URL, and check that its ok. 
         If ok, include jQuery from Google CDN. 
         */
         if(200 === wp_remote_retrieve_response_code(wp_remote_head($google_jquery_url))) {
         wp_deregister_script('jquery');
         wp_register_script('jquery', $google_jquery_url , false, null, $cdn_script_in_footer);
         }
      }
   }
   /* 
   Enqueue jQuery from Google if available. 
   Fall back to the local WordPress default.
   If the local WordPress jQuery is called, it will get 
   included in the header no matter what the 
   $cdn_script_in_footer flag above is set to.
   */
   wp_enqueue_script('jquery'); 
}
add_action('wp_enqueue_scripts', 'appglobe_jquery_enqueue', 11);

14 Responses

  1. John says:

    Why not use the latest version instead, like so:
    http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js

    or

    http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js

    • The caching benefit will vanish. The less specific URLs have very short caching. Only 1 hour or so, while the URL with the full version have a year.
      You can try them here:

      http://www.webconfs.com/http-header-check.php

      I belive the unspecific versions are for developing purpose only. If, however, you’d like to use the less specific ones anyway, you could split up the local wordpress version in the function above like this:

      $registered_jquery_version_arr = $pieces = explode(".", $registered_jquery_version);
      $registered_jquery_version_base = "1";
      if(!empty($registered_jquery_version_arr)) {
         $registered_jquery_version_base = $registered_jquery_version_arr[0]; 
         $google_jquery_url = ($_SERVER['SERVER_PORT'] == 443 ? "https" : "http") .                                
         "://ajax.googleapis.com/ajax/libs/jquery/$registered_jquery_version_base/jquery.min.js";
      }

      But I wouldn’t recommend it!

  2. Keith says:

    What if you want the latest 1.8.x version?

  3. Sandy says:

    Google should allow for a GET -parameter to extend the caching time.

  4. Mitcha says:

    Lets hope next WordPress update includes jQuery 1.8.

    • Krishna says:

      Head on over to Google Libraries API and see if you can take advantage of this great secrvie. If you are running WordPress, check out an article that I wrote earlier on How To Use Google Hosted jQuery In Your WordPress Theme.

  5. James Payne says:

    Thanks for this great way of loading via the Google CDN, but I can’t for the life of me get the script to load in the footer. I’ve tried setting $cdn_script_in_footer = true; but the script is still loading in the head.

    Any ideas why?

  6. @James Payne, perhaps trying a different value for the priority parameter of add_action might help?
    For example:
    add_action("wp_enqueue_scripts", "appglobe_jquery_enqueue", 1)

    If that does’t help you could set the in_footer parameter of wp_enqueue_script to true as well to see if that helps.

    I purposely did not want to use default loading in footer since you would run the risk of breaking stuff that need jQuery loaded early.

  7. James Payne says:

    Hi @Martin Carlsson,

    neither of those suggestions worked 🙁 I’m wondering if it’s a theme conflict? I’m using Woothemes Canvas 5.1

    It’s not really a problem with it loading in the head, I just find it strange why it won’t change.

    James

    • I guess you’ve checked that you have wp_footer() in your your footer.php theme file?

      Also, have you tried switching theme temporary?

      You could try and force scripts to the footer:

      remove_action('wp_head', 'wp_print_scripts');
      remove_action('wp_head', 'wp_enqueue_scripts', 1);
      add_action('wp_footer', 'wp_print_scripts', 5);
      add_action('wp_footer', 'wp_enqueue_scripts', 5);
      

      but some plugins might need to have scripts loaded in the head…might break stuff.