3

Note: Removing jQuery that comes with Wordpress is not recommended. Use caution if implementing the solution below

I have a few pages that will not require jQuery to be loaded in the header. I'm wondering if it's possible to dequeue/deregister WordPress jQuery and enqueue/register jQuery cdn on specific pages?

I've read through the do's and don'ts but we aren't using any plugins and the theme is custom.

Below is my current code but it does't seem to want to work. The default Wordpress jQuery still loads in the header.

if (!function_exists('modify_jquery')) {
    function modify_jquery() {
        if (is_page(array('page 1', 'page 2'))) {
            wp_dequeue_script('jquery');
            wp_deregister_script('jquery');

            wp_register_script('jquery-custom', '//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js', false, '1.11.3', 'true');
            wp_enqueue_script('jquery-custom');
        }
    }
}
add_action('init', 'modify_jquery');
3
  • 1
    That code doesn't remove jQuery, it replaces it with the google API AJAX version. You shouldn't do this as it introduces compatibility problems with other plugins and code, and even WP Core itself. Always use the version that comes with WordPress. Also keep in mind that you've tied yourself to a specific version of jQuery, and won't get any of the newer updates with fixes
    – Tom J Nowell
    Aug 19, 2016 at 22:38
  • I'm actually only doing this on a few pages of the site and was also testing to see if it actually improved my page speed score with Google...it didn't. Would the above affect WP Core? I figured since I was calling it out on specific pages that it would not affect core. I'll add a note in bold at the top of my question.
    – brandozz
    Aug 20, 2016 at 19:17
  • I couldn't answer that question as it would require knowledge of future versions of WordPress that haven't been written yet
    – Tom J Nowell
    Aug 20, 2016 at 23:44

1 Answer 1

6

Hook to wp_enqueue_scripts. It will do the trick.

Modified code is-

if (!function_exists('modify_jquery')) {
    function modify_jquery() {
        if (is_page(array('page 1', 'page 2'))) {
            wp_dequeue_script('jquery');
            wp_deregister_script('jquery');

            wp_register_script('jquery-custom', '//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js', false, '1.11.3', 'true');
            wp_enqueue_script('jquery-custom');
        }
    }
}
// add_action('init', 'modify_jquery');
add_action('wp_enqueue_scripts', 'modify_jquery');

Hope this is gonna help.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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