1

我正在尝试从 CDN 加载 jquery,而不是使用 wordpress 本地加载。在我的functions.php中,我已经完成了如下操作,确保它应该只发生在前端:

function replace_jquery() {
    if (!is_admin()) {
        wp_deregister_script('jquery');
        wp_register_script('jquery2', 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js');
        wp_enqueue_script('jquery2');
    }
}
add_action('init', 'replace_jquery');

尽管如此,当我尝试登录管理区域时,我收到一堆错误,开头是:

Notice: wp_deregister_script was called <strong>incorrectly</strong>. 
Do not deregister the <code>jquery</code> script in the administration area. 
To target the front-end theme, use the <code>wp_enqueue_scripts</code> hook. 
Please see <a href="https://codex.wordpress.org/Debugging_in_WordPress">Debugging in WordPress</a> for more information. 
(This message was added in version 3.6.0.) in /app/public/wp-includes/functions.php on line 4204

有时它不会抛出这个错误,有时它会。我究竟做错了什么?

4

1 回答 1

2

多年来,这个问题已经被处理了很多次,实际上它是相当重复的,但无论如何我会尝试总结/更新“最佳实践”方法。

1. 不要替换默认的 WordPress jQuery,除非你真的必须这样做。如果您真的关心性能,则不需要 jquery

2.除非你的主题或插件确实加载了jQuery,否则WordPress默认不会在前端加载它,通常我们必须使用wp_enqueue_script('jquery');它来加载它。所以首先,确保你有 jQuery 入队。使用此代码段检查您的排队脚本:

// Show all enqueued scripts
add_action( 'wp_print_scripts', function () {
    global $wp_scripts;
    $enqueued_scripts = array();
    foreach( $wp_scripts->queue as $handle ) {
        $enqueued_scripts[] = $wp_scripts->registered[$handle]->src;
    }
    var_dump($enqueued_scripts);
} );

3.不要使用错误的action hook init来添加你的脚本,你应该使用wp_enqueue_scripts来代替。

有专门的保护措施来防止关键的管理脚本(例如 jQuery 核心)被取消注册。资源

4.大多数替换默认jquery的解决方案都过时了。请改用此代码(在 WP v5.1 上测试):

// Replace the default wp jquery with fallback
add_filter( 'wp_enqueue_scripts', 'replace_default_jquery_with_fallback');
function replace_default_jquery_with_fallback() {
    // Change the version if needed
    $ver = '1.12.4';
    // Dequeue first then deregister
    wp_dequeue_script( 'jquery' );
    wp_deregister_script( 'jquery' );
    // Load from Google
    // Set last parameter to 'true' if you want to load it in footer
    wp_register_script( 'jquery', "//ajax.googleapis.com/ajax/libs/jquery/$ver/jquery.min.js", '', $ver, false );
    // Fallback
    wp_add_inline_script( 'jquery', 'window.jQuery||document.write(\'<script src="'.includes_url( '/js/jquery/jquery.js' ).'"><\/script>\')' );
    wp_enqueue_script ( 'jquery' );
}

请注意:

  • 使用这种方式也会影响任何依赖 jQuery 的插件
  • 完全删除样式或脚本的正确方法是先将其出列然后取消注册
  • init动作钩子是“在 WordPress 完成加载后但在发送任何标头之前触发”小心使用它。
  • wp_enqueue_scripts用于处理前端脚本。
  • admin_enqueue_scripts用于处理管理脚本
  • login_enqueue_scripts用于登录页面
  • 如果您的代码/插件是为早于 1.9 的 jQuery 版本开发的,请考虑使用jQuery Migrate 。
于 2019-02-26T12:46:43.350 回答