Colorlib

How to Load WordPress jQuery Script From CDN (Google Hosted Libraries)

This tutorial will show you how to replace your local jQuery script which comes with WordPress with one from from Google Library for better performance and reliability. This usually is done optimize website performance and improve website load speed for relatively slow shared hosts. Use of CDN (Google Library in this case) is a great way to reduce load on your server in unexpected traffic spike as less files will be loaded from your server and load would be distributed over Google server infrastructure.

In case you are using your own VPS I wouldn’t recommend to load jQuery from other resources but would minify, combine and gzip it locally which does require some JavaScript skills to combat JavaScript and jQuery conflicts but it is worth it.

What are the benefits from using Google Library CDN for jQuery and other JavaScript libraries?

1. Better performance as Google surely has a better server than you have.
2. jQuery file from Google Library might be already cache 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

As you can all benefits are related to website performance and most likely you read this because you are looking to improve your website performance, am I right?

How to loads jQuery from Google Library (CDN)

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 other place outside WordPress code)
  3. Array of any scripts which depend on this script (in most case scripts will depend on jQuery but there are many uses of this)
  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 avoid using Google Library for jQuery?

What are your thoughts about loading jQuery from Google Library or other CDN resources that are dedicated to JavaScript libraries? CDN as a whole for images, scripts and other large files is a whole other story but what about this?

Update Spazlport have provided useful code snippet in comment section below for those looking for even more advanced solution.