3

I've been using the code below to use Google's jQuery but the latest WordPress version deactivated it. How can I use jQuery from Google?

//* Use Google's jQuery
add_action('init', 'use_jquery_from_google');

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

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

    wp_deregister_script('jquery');
    wp_register_script('jquery', "//ajax.googleapis.com/ajax/libs/jquery/$ver/jquery.min.js", false, $ver);
}
  • 2
    Are you sure using the Google CDN is actually faster? – Tom J Nowell May 22 at 14:21
  • I don't know, to be honest. It was just something that was suggested. Are you saying I shouldn't use the Google CDN? – Desi May 22 at 14:31
  • When you say deactivated do you know specifically what is happening? WordPress isn't calling your handler, or it's aborting at the is_admin check, or it's ignoring your attempts to change the jquery script registration, or something else? Does it still include the local copy of jquery? Does it not include jquery at all? – Rup May 22 at 14:33
  • @Desi sometimes it's faster, sometimes it isn't, but it's almost universally parrotted as a bonus without anybody ever testing if it improves things. As for 5.2, there's nothing in 5.2 that would stop this from working that I know of. jquery-core lists jquery as a dependent anyway – Tom J Nowell May 22 at 14:38
8

5.2.1 includes a backported fix from jQuery 3.4.0 (commit). Because they're now using a modified version of jQuery they suffixed the version number with '-wp':

$scripts->add( 'jquery', false, array( 'jquery-core', 'jquery-migrate' ), '1.12.4-wp' );

Your code tries to copy the jQuery version number from the existing registration

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

The problem is that Google's CDN won't have a version of jQuery called 1.12.4-wp. The following URL

https://ajax.googleapis.com/ajax/libs/jquery/1.12.4-wp/jquery.min.js

doesn't exist. The same URL without the '-wp' does work. So the error you should be seeing in your browser console is a 404 loading jQuery from the CDN.

The jQuery patch is to fix Trac 47020 which is a security issue in jQuery.extend that could allow cross-site scripting attacks ("Minor vulnerability fix: Object.prototype pollution"). So you probably do want it, either by using WordPress's patched version of 1.2.14 again or by updating to 3.4.0 (if that's compatible with the rest of your site).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.