3

Hi I was looking for a way to move wordpress default jQuery to the footer and I saw this answer: https://wordpress.stackexchange.com/a/225936/50584

So, I tried this approach in my child theme's functions.php file:

add_action( 'wp_enqueue_scripts', function() {
    // Move jQuery to the footer
    wp_scripts()->add_data( 'jquery', 'group', 1 );
    wp_scripts()->add_data( 'jquery-core', 'group', 1 );
    wp_scripts()->add_data( 'jquery-migrate', 'group', 1 );
});

But it is not pushing jquery to the footer. Any idea guys why is this happening? I want to avoid the de-register & re-register way of doing this.

Any help will be highly appreciated.


Important Update: Since WP v3.9 there is no way of putting jquery scripts in your footer rather than using the de-register & re-register option. It is just simply cannot be done as the author pointed out below.

2

You should use the param $scripts of the hook wp_default_scripts. In this hook was en-queued all default scripts, also jQuery and you can change his data, like the group for load in footer.

add_action( 'wp_default_scripts', '_print_jquery_in_footer' );
function _print_jquery_in_footer( $scripts ) {

    if ( ! is_admin() )
        $scripts->add_data( 'jquery', 'group', 1 );
}

Also in the newer code style via anonymous function, like your question example; possible since php 5.3:

add_action(
    'wp_default_scripts',
    function( $scripts ) {
        if ( ! is_admin() )
            $scripts->add_data( 'jquery', 'group', 1 );
    }
);

Edit: This will only work with WordPress versions lower than 3.9!

  • You didn't need to reedit your question for the anonymous function. I got your point brother. Thanks a ton. Let me try it out real quick. – iSaumya Aug 31 '16 at 12:35
  • 1
    The reason I hate de-rester process is because there are many dependent script that relies on the jQuery version and in most cases people pass null or a blank string as the jQuery version which is not good. Though you can manually enter the version, but every time wordpress will update the script you need to update your script again. Not a good way to do it. I'm actually making this function is a small plugin file and then I'm gonna put in in mu-plugins folder rather than putting in functions.php. Thanks again. – iSaumya Aug 31 '16 at 12:37
  • The source will not work since WP 3.9, sorry. I have forgotton. But see this comments why have WP change this - wpengineer.com/2482/enqueue-bundled-jquery-in-footer – bueltge Aug 31 '16 at 13:12
  • Hi there I just looked at your site. But you are using the same thing I'm using I really don't got the point here you are trying to make – iSaumya Aug 31 '16 at 13:15
  • 1
    Yes, I think so. – bueltge Aug 31 '16 at 13:32

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.