Support » Developing with WordPress » How to move the jQuery in the footer?

  • Hello,
    I have a problem with moving jquery via CDN, I’ve tried many solutions in this forum and on Stack Overflow but I can’t find a solution to migarate the script in the footer.

    I currently use the following code to invoke the script:

    add_action('wp_enqueue_scripts', 'load_jquery');
    
    function load_jquery() {
        global $wp_scripts;
        if(is_admin()) return;
        $wp_scripts->registered['jquery-core']->src = 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js';
        $wp_scripts->registered['jquery']->deps = ['jquery-core'];
    }

    This below is one of the many scripts found in the form to be able to move the jquery into the footer but it doesn’t work:

    function jquery_mumbo_jumbo()
    {
        wp_dequeue_script('jquery');
        wp_dequeue_script('jquery-core');
        wp_dequeue_script('jquery-migrate');
        wp_enqueue_script('jquery', false, array(), false, true);
        wp_enqueue_script('jquery-core', false, array(), false, true);
        wp_enqueue_script('jquery-migrate', false, array(), false, true);
    }
    add_action('wp_enqueue_scripts', 'jquery_mumbo_jumbo');

    any ideas to fix this?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    To override the default registered jQuery module sources, dequeuing is not adequate. You must dergister the default and re-register using your preferred arguments. You don’t really need to enqueue jQuery in most cases because the scripts that rely upon it should be enqueued while specifying ['jquery'] as the dependencies argument. This then enqueues jQuery and any of its dependencies by reference.

    Obje

    (@harrow)

    Hi there,

    I have the exact same issue.
    In order to move jQuery into my websites footer, I used to add the following code to my functions.php file :

    function sp_register_assets() {   
      wp_deregister_script( 'jquery' );
      wp_enqueue_script(
        'jquery', 
        'https://code.jquery.com/jquery-2.2.4.min.js', false, NULL, true 
      );
    }
    add_action( 'wp_enqueue_scripts', 'sp_register_assets' );
    recently I've tried this code, but without effect... 
    function move_jquery_to_footer() {
        wp_scripts()->add_data( 'jquery', 'group', 1 );
        wp_scripts()->add_data( 'jquery-core', 'group', 1 );
        wp_scripts()->add_data( 'jquery-migrate', 'group', 1 );
    }
    add_action( 'wp_enqueue_scripts', 'move_jquery_to_footer' );

    Does anyone knows what could be the reasons why jQuery can’t be loaded into the footer?

    Thanks by advance

Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.