Wordpress Tutorial: Load the jQuery Library from CDN

Posted by Ronald Eddy on Wednesday, May 23, 2012

Some might say there is really just 1 thing to remember about making good Wordpress website. Make it fast. Speeding up your Wordpress site will improve user experience and also improve your sites SEO. Using a CDN to distribute your jQuery library is a great place to start.

There are at least 4 reasons you should use a CDN to service jQuery on your page:

  1. Decreased Latency
    Content Delivery Network — distributes your static content across servers in various physical locations. The User’s download will automatically target the closest available server in the network.

  2. Increased parallelism
    To avoid needlessly overloading servers, browsers limit the number of connections that can be made simultaneously. Depending on which browser, this limit may be as low as two connections per hostname.

  3. Better caching
    Potentially the greatest benefit of using the Google AJAX Libraries CDN is that your users may not need to download jQuery at all. If your user had downloaded the content in the past, it may already be cached.

  4. Reduced bandwidth costs
    If someone else’s CDN is pushing the content to your users, they are using their bandwidth, not yours.

All of these reasons add up to fast responsive websites. That may be the one thing that everyone agrees is a good thing.

Wordpress: Google’s jQuery CDN

I spend a good amount of time working in Wordpress environments. Seems like every theme comes with jQuery and the all use the local copy, obviously that is not a great idea, luckly there is a simple way to correct this oversight with just 6 lines of code.

functions.php file

function jquery_cdn() {
   if (!is_admin()) {
      wp_deregister_script('jquery');
      wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js', false, '2.1.3');
      wp_enqueue_script('jquery');
      }
   }
add_action('init', 'jquery_cdn'); 

Other jQuery CDN options

While I recommend using the Google CDN because it is so widely used and therefore increases the changes it will already be in your user’s cache, there are several other options.

Google’s jQuery CDN
https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js

Microsoft’s jQuery CDN
http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.3.min.js

jQuery’s CDN
https://code.jquery.com/jquery-2.1.3.min.js

Other jQuery CDN Version Options

Most of the CNDs listed above will also service other versions of jQuery. For example if you wish to use jQuery 1.5.2 from Google’s CDN it is simply a matter of requesting http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js

Complete jQuery CDN Version Listings


comments powered by Disqus