Load jQuery From Google CDN into your WordPress

jQuery is almost a must have Javascript library for any web developer. By default, WordPress loads a copy of jQuery library into your website so that it can be available for use.

As professional WordPress developers and for performance reasons, We always load the jQuery library from Google CDN.  Enqueuing jQuery from Google CDN minimizes HTTP requests to your server and makes your website load even faster which contributes positively to SEO.

The code snippet provided below will help you deregister the jQuery file loaded by WordPress and will enqueue it from Google’s code repository.  Which means the snippet is coded in such a way to load only one jQuery file. It loads only the one from the CDN of Google.

PHP
// Load jquery from Google code repository CDN

add_action( 'init', 'wph_google_jquery' );

function wph_google_jquery() {

	if ( !is_admin() ) {
	    
	    wp_deregister_script( 'jquery' );
	    
	    wp_register_script( 'jquery', ( 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js' ), false, null, true );
	    
	    wp_enqueue_script( 'jquery' );
	
	}

}

If you prefer to load jQuery from another external server other than Google’s scripts repository don’t worry. There are many other scripts CDN alternatives which you can use for free. For example, the following CDN services will let you load whichever version of jQuery you need:

  • Jsdeliver: https://cdn.jsdelivr.net/jquery/3.2.1/jquery.min.js
  • Dnjs: https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.jsCopy
  • Microsoft: http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js

These are just some of the available options for loading jQuery from external servers. Make sure though to update the link in the snippet above with the source link you prefer.