wp_enqueue_script

wp_enqueue_script( string $handle, string $src = '', array $deps = array(), string|bool|null $ver = false, bool $in_footer = false )
很明显最后一个参数 $in_footer 设置为 True 时,js 文件会被加载到文档底部。

核心 Jquery 文件

wordpress 内置了 jquery 类库。但默认是加载在页面头部的。
有两种方式, 一种先是删除核心的 jquery 包,再引自定义的 jquery 包到底部:

 function my_scripts_method() {
        wp_deregister_script( 'jquery' );
        wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js', true );
        wp_enqueue_script( 'jquery' );
 }
add_action('wp_enqueue_scripts', 'my_scripts_method');

另一种方式是有人读了wp_enqueque_script 的代码实现,如下:

function wp_register_script( $handle, $src, $deps = array(), $ver = false, $in_footer = false ) {
        $wp_scripts = wp_scripts();
        _wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );

        $registered = $wp_scripts->add( $handle, $src, $deps, $ver );
        if ( $in_footer ) {
                $wp_scripts->add_data( $handle, 'group', 1 );
        }

        return $registered;
}

所以正确的解决方案为:

add_action( 'wp_default_scripts', 'move_jquery_into_footer' );

function move_jquery_into_footer( $wp_scripts ) {

    if( is_admin() ) {
        return;
    }

    $wp_scripts->add_data( 'jquery', 'group', 1 );
    $wp_scripts->add_data( 'jquery-core', 'group', 1 );
    $wp_scripts->add_data( 'jquery-migrate', 'group', 1 );
}

REFs

https://developer.wordpress.org/reference/functions/wp_enqueue_script/
https://wordpress.stackexchange.com/questions/173601/enqueue-core-jquery-in-the-footer

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-01
  • 2021-11-04
  • 2022-01-04
猜你喜欢
  • 2021-06-16
  • 2022-01-30
  • 2022-01-24
  • 2021-10-08
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案