Wordpress 加载 js 文件到底部

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值