2

I have jQuery setup in my enqueue scripts section as a dependency, such as:

wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'scripts', get_template_directory_uri() . '/js/scripts.min.js', array( 'jquery' ) );

Now, I want to remove jquery-migrate, but keep jQuery itself obviously, so I found this answer stating to do it like this:

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

Firstly, I thought we had removed jQuery migrate here, so not sure what the need of adding the latest version of it is with the comment:

1.2.1 = latest version of jquery-migrate

Secondly, with the way I set my enqueue scripts up, how does that affect the dependencies since I have now removed jQuery and added jquery-core?

Is there a better way to handle this?

2
+50

First part...

OK, so in your theme/plugin you have:

wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'scripts', get_template_directory_uri() . '/js/scripts.min.js', array( 'jquery' ) );

The first line, enqueuing jquery isn't necessary - you put jquery as dependency in second line, so it will be included anyway.

These lines inform WP that you want to enqueue given file as scripts and it needs script registered with handle jquery - so it will be enqueued automatically before your script.

And the second part...

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

As you can see in Plugin API/Action Reference, this hook is called pretty early... Waaaaay before wp_enqueue_scripts.

And what it really does?

It removes script with handle jquery from default scripts, and then adds it with different dependencies (only jquery-core).

add method comes from WP_Dependencies class:

WP_Dependencies::add( string $handle, string $src, array $deps = array(), string|bool|null $ver = false, mixed $args = null )

And why that version?

The version 1.2.1 is just a cache booster. WordPress does not analyze it. It is used as ?ver param, so browsers have to reload that file, when the version changes... You can put anything in there - of course using real version of given script is a good idea ;)

  • That's excellent - thanks very much. Any idea how to get it placed in the footer? I couldn't quite understand what to pass to it with regards to the args parameter. – Brett Jul 26 '18 at 13:17

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.