How to Load WordPress jQuery Script From Google Hosted Library to Improve Speed

jQuery is one of the most used scripts in plugins and themes for WordPress. For better performance and reliability, local jQuery script can be replaced with one from Google Library. Google Library has become the standards for including scripts in web design as they are using Google’s CDN which is extremely powerful.This usually is done to optimize website performance and improve website load speed for relatively slow shared hosts.

Why use Google Library CDN for jQuery and other JavaScript libraries?

  1. Google can ensure better performance as they have better servers than you have.
  2. jQuery file from Google Library might be already cached in your visitors’ browser making to load it even faster.
  3. jQuery is loaded from the closest Google server.
  4. Less load on your server.

How to load jQuery from Google Library

First of all default WordPress scripts are registered via functions.php file and there are five parameters for this function.

wp_register_script
  1. Name (jQuery on our case)
  2. URL of script (if it is loaded from theme folder or another place outside WordPress code)
  3. Array of any scripts which depend on this script (in most case scripts will depend on jQuery)
  4. Script version number (Only optional to keep the track of scripts you have installed)
  5. In the footer. (by default it is set to load all scripts in header, if this parameter is set “true”, scripts will be loaded in footer instead )
//Making jQuery to load from Google Library
function replace_jquery() {
    if (!is_admin()) {
        // comment out the next two lines to load the local copy of jQuery
        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js', false, '1.11.3');
        wp_enqueue_script('jquery');
    }
}
add_action('init', 'replace_jquery');

When and why should you not use Google Library for jQuery?

  • You should not do this on theme’s or plugin’s that you will not be controlling forever (i.e client sites, free/commercial theme or plugin that you want to distribute to the masses).
  • When developing WordPress based website for your clients that you won’t maintain. Again the script will get outdated.
  • If you are on your own VPS you won’t get any speed benefits. If you did know how to setup your own VPS it is likely that you will know how to implement caching, gzip and script minification.

sarah ali

sarah ali

Sarah is a passionate writer and blogger. As an early adopter, she enjoys trying out new social media and Internet tools along with WordPress plugins and Web apps.
sarah ali

Leave a Reply

Your email address will not be published.