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.
Comments