Load jQuery from Google’s CDN in WordPress

WordPress loads jQuery from your server by default. It’s much better to load jQuery from Google’s CDN (content delivery network). Here are the 4 main reasons:

  1. Your visitors probably already have jQuery from Google’s CDN cached. This means jQuery will load nearly instantly.
  2. It’s probably faster to load jQuery from Google’s servers than your servers. They have faster servers and better networks. They also probably have a data center that’s closer to your visitor.
  3. Browsers will download jQuery in parallel with your local scripts. Browsers usually limit concurrent downloads to 4-8 from the same domain.
  4. You get to save on bandwidth.

You should load jQuery from a CDN 99.9% of the time. If you don’t want to use Google’s CDN, you can use a CDN from cdnjs or jQuery.

Here’s the code to load jQuery from Google’s CDN:

add_action('init', function() {
	if (is_admin()) {

	global $wp_scripts;
	if (isset($wp_scripts->registered['jquery']->ver)) {
		$ver = $wp_scripts->registered['jquery']->ver;
	} else {
		$ver = '1.12.4';

	wp_register_script('jquery', "//ajax.googleapis.com/ajax/libs/jquery/$ver/jquery.min.js", false, $ver);

You may notice that this is pretty different from most other snippets you’ve seen. Here are the differences and the explanations for them:

1. Using the version from $wp_scripts instead of a hardcoded value

If you update WordPress, the version of jQuery that it wants may change. If you hardcode the version, you have to change it when you update WordPress. My snippet automatically loads the version that WordPress wants. If $wp_scripts doesn’t contain the version for whatever reason (it should never happen), it defaults to 1.12.4. This is the jQuery version requested by the latest version of WordPress at the time of writing.

2. Not calling wp_enqueue_script

Not all WordPress blogs use jQuery, aside from the admin section. My snippet merely replaces the URL to load jQuery from. If your blog needs jQuery, it will enqueue it itself.

3. Using a relative URL

If you use a non-secure URL (i.e. http://)  to load jQuery, it won’t load if you access a secure version of your blog.

For reference, here is the snippet from WPBeginner, which is the top result on Google:

//Making jQuery Google API
function modify_jquery() {
	if (!is_admin()) {
		// comment out the next two lines to load the local copy of jQuery
		wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js', false, '1.8.1');
add_action('init', 'modify_jquery');

(retrieved on July 20th, 2016)

Leave a Reply

Your email address will not be published. Required fields are marked *