How to add jQuery to WordPress using a CDN

Marc Wag­ner

July 2, 2021

1 min read|

jQuery is often used for addi­tio­nal scripts. The­r­e­for, even if you use HTTP2, a fast deploy­ment is recom­men­ded to avo­id unneces­sa­ry blo­cking time. In some cases, it’s easier and fas­ter to switch to a CDN.

The fol­lo­wing code dis­plays, how you can easi­ly out­sour­ce your jQuery to a CDN. This code can be copied into your functions.php file within your the­me direc­to­ry.

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 ver­si­on with the link to the Goog­le CDN. We also add a ver­si­on check to ensu­re future com­pa­ti­bi­li­ty.

We hope you enjoy­ed this short gui­de about how to add jQuery to Word­Press using a CDN. If you have ques­ti­ons, feel free to place a com­ment below.

88e86fcb816eff22bc917094df2862d8dd5c0e978b333e6dd5f36f808990c261 96

Arti­kel von:

Marc Wag­ner

Hi Marc here. I’m the foun­der of Forge12 Inter­ac­ti­ve and have been pas­sio­na­te about buil­ding web­sites, online stores, appli­ca­ti­ons and SaaS solu­ti­ons for busi­nesses for over 20 years. Befo­re foun­ding the com­pa­ny, I alre­a­dy work­ed in publicly lis­ted com­pa­nies and acqui­red all kinds of know­ledge. Now I want to pass this know­ledge on to my cus­to­mers.

Hast du eine Fra­ge? Hin­ter­lass bit­te einen Kom­men­tar