How and Why to Use Modern jQuery in WordPress

Posted on Updated on WordPress by Adam Laki

One of WordPress’s significant dependency is jQuery. Usually, it is hard to remove from our front-end entirely, but we surely can optimize it.

A lot of developers don’t like WordPress because of the legacy code (support) that comes from the generous backward compatibility thinking. Fortunately, lately, this started to change, and now the core developers began to drop the older PHP support. Which we can genuinely welcome.

jQuery, One of The Biggest Dependency

Of course, because WordPress is a monster, this isn’t easy. Today by default, WP loading the jQuery 1.x version, which is old and full of unnecessary code (and browser support). We also load jQuery Migrate, and all of this costs us tens of kilobytes in size alone.

Because of the big ecosystem, it is hard to pull this dependency out, but we hope that someday we will have more options. Today most of the plugins are run on jQuery; some of them rely on an older one. To remove it entirely is almost impossible today, but we can optimize it with a newer version.

Change The jQuery Version

To switch the jQuery versions we need to use the wp_enqueue_scripts action and the $wp_scripts global variable. We want to switch it on the front-end (which is our best option), so we will also check if it isn’t loading on the admin screen.

Place the following code snippet into your theme’s functions.php or anywhere where it will run:

function pine_change_jquery_version() {
    global $wp_scripts;
    if( is_admin() ) {
        return;
    }

    $wp_scripts->registered['jquery-core']->src = get_stylesheet_directory_uri() .'/node_modules/jquery/dist/jquery.min.js';
    $wp_scripts->registered['jquery-core']->ver = '3.5.1';
    $wp_scripts->registered['jquery']->deps = ['jquery-core'];
}

add_action('wp_enqueue_scripts', 'pine_change_jquery_version');

As you see, the code is self-explanatory. In the $wp_scripts we can find our active dependencies like jQuery. First, we have to overwrite jquery-core‘s src and ver value. After this, we have to overwrite the jquery dependency’s deps value with the newly declared core section. With the last line, we also dropped the migrate dependency (removed it from the dependencies).

Need a web developer? Maybe we can help, get in touch!