duanqiao9541 2014-02-20 07:09
浏览 78
已采纳

如何在页脚中加载WordPress提供的jQuery?

Setting the $in_footer parameter to true in wp_enqueue_script loads a script in the footer. This is great if I'm adding a new script. However, WordPress already provides a version of jQuery by default and this is enqueued in the document head.

How can I move the jQuery provided by WordPress from the header to the footer?

  • 写回答

1条回答 默认 最新

  • duanmu2013 2014-02-20 08:56
    关注

    You need to de-register the existing query and re-register it to load in the footer.

    function jquery_in_footer() {
        if (!is_admin()) {
            wp_deregister_script('jquery');
    
            // load the local copy of jQuery in the footer
            wp_register_script('jquery', home_url(trailingslashit(WPINC) . 'js/jquery/jquery.js'), false, null, true);
    
    
            wp_enqueue_script('jquery');
        }
    }
    add_action('init', 'jquery_in_footer');
    

    Bear in mind that if you have any other scripts enqueued that depend on jQuery and are not loaded in the footer, WordPress will still load jQuery in the header to satisfy that dependency.

    (adapted from http://www.ericmmartin.com/5-tips-for-using-jquery-with-wordpress/)

    Edit: If you really want to get crazy, you could modify the WP_Scripts object directly, but then you're dependent on the implementation never changing. I imagine that would change before they even thought of moving jquery.js' location in wp-includes :)

    But just for fun…

    function load_jquery_footer() {
        global $wp_scripts;
        $wp_scripts->in_footer[] = 'jquery';
    }
    add_action('wp_print_scripts', 'load_jquery_footer');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部