How to add jQuery to WordPress using a CDN

Marc Wagner, July 2, 2021

jQuery is often used for additional scripts. Therefor, even if you use HTTP2, a fast deployment is recommended to avoid unnecessary blocking time. In some cases, it’s easier and faster to switch to a CDN.

The following code displays, how you can easily outsource your jQuery to a CDN. This code can be copied into your functions.php file within your theme directory.

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 the Google CDN. We also add a version check to ensure future compatibility.

We hope you enjoyed this short guide about how to add jQuery to WordPress using a CDN. If you have questions, feel free to place a comment below.

Avatar of Marc Wagner
Marc Wagner

Hi Marc here. I'm the founder of Forge12 Interactive and have been passionate about building websites, online stores, applications and SaaS solutions for businesses for over 20 years. Before founding the company, I already worked in publicly listed companies and acquired all kinds of knowledge. Now I want to pass this knowledge on to my customers.

Similar Topics

Comments

Leave A Comment