Loading jQuery in the footer after removing jQuery migrate?

I am removing jQuery migrate in WordPress in this way:

add_filter( 'wp_default_scripts', 'remove_jquery_migrate' );

function remove_jquery_migrate( $scripts ){
    if(!is_admin()){
        $scripts-remove( 'jquery');
        $scripts-add( 'jquery', false, array( 'jquery-core' ), '1.2.1');
    }
}

I'm confused at how you set the in_footer property with the WP_Dependencies::add function, I tried the below but it didn't work:

$scripts-add( 'jquery', false, array( 'jquery-core' ), '1.2.1', ['in_footer' = true]);

What is the correct way to do this?

Topic wp-dependencies scripts php jquery Wordpress

Category Web


There is much safer way of removing jquery-migrate... Your code is almost correct, but first you remove jQuery and then add it again. If dependencies for jQuery will change, then your code will cause problems.

But you don't have to remove script to change its dependencies. You can do exactly that:

function remove_jquery_migrate( $scripts ) {
    if ( ! is_admin() && isset( $scripts->registered['jquery'] ) ) {
        $script = $scripts->registered['jquery'];

        if ( $script->deps ) {
            $script->deps = array_diff( $script->deps, array( 'jquery-migrate' ) );
        }
    }
} 
add_action( 'wp_default_scripts', 'remove_jquery_migrate' );

It's much safer, since we remove only one dependency that we want to be removed.

And if you want to move jQuery to footer, then you can use this code:

function remove_jquery_migrate( $scripts ) {
    if ( ! is_admin() && isset( $scripts->registered['jquery'] ) ) {
        $script = $scripts->registered['jquery'];

        if ( $script->deps ) {
            $script->deps = array_diff( $script->deps, array( 'jquery-migrate' ) );
        }

        $scripts->add_data( 'jquery', 'group', 1 );
        $scripts->add_data( 'jquery-core', 'group', 1 );
    }
} 
add_action( 'wp_default_scripts', 'remove_jquery_migrate' );

Again - we don't remove any scripts and add our own, but modify existing scripts only, so it's much more secure approach.


That is correct but you did supply a new source.

Replace:

$scripts->add( 'jquery', false, array( 'jquery-core' ), '1.2.1', ['in_footer' => true]);

With:

$scripts->add( 'jquery', 'http://new-url/', array( 'jquery-core' ), '1.2.1', ['in_footer' => true]);

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.