Deregister WordPress jquery on specific page

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');

1 Answer
1

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.

Leave a Comment