Build noteFeb 08, 2021

How to Include jQuery for WordPress via a CDN

jQuery is often required for additional scripts, so a quick delivery is sensible despite HTTP2 to avoid unnecessary blocking. In some cases, it makes sense to switch to a CDN.

We have illustrated how this works in the following code. You can simply insert this into the Functions.php of your child theme.

add_action( 'init', 'loadJQueryByCDN', 20 );

function loadJQueryByCDN(){
	if ( is_admin() ) {
		return;
	}

	$protocol = is_ssl() ? 'https' : 'http';

	/** @var WP_Scripts $wp_scripts */
	global $wp_scripts;

	/** @var _WP_Dependency $core */
	$core         = $wp_scripts->registered['jquery-core'];
	$core_version = $core->ver;
	$core->src    = "$protocol://ajax.googleapis.com/ajax/libs/jquery/$core_version/jquery.min.js";

	/** @var _WP_Dependency $jquery */
	$jquery       = $wp_scripts->registered['jquery'];
	$jquery->deps = [ 'jquery-core' ];
}

The script replaces the link of the local jQuery version with the link to Google. To also support future changes from WordPress to the jQuery version, we additionally query the version being used and append it to the Google link.

If this post helped you, we would appreciate a comment.