用外部托管替换本地 jQuery 时出现 Wordpress 错误

Wordpress error when replacing local jQuery by externally-hosted

我正在尝试从 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

这个错误有时不报,有时报。我做错了什么?

这个问题多年来已经被处理了很多次,实际上它是重复的,但无论如何我会尝试summarize/update "Best practice" 方法。

1. Do not replace the default WordPress jQuery unless you really have to. If you really care about performance you don't need 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.不要使用错误的动作挂钩init for adding your scripts, you should use wp_enqueue_scripts代替。

There are intentional safeguards in place to prevent critical admin scripts, such as jQuery core, from being unregistered. source

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 动作挂钩 "Fires after WordPress has finished loading but before any headers are sent" 小心使用。
  • wp_enqueue_scripts用于处理前端脚本。
  • admin_enqueue_scripts 用于处理 管理脚本
  • login_enqueue_scripts 用于 登录页面
  • 如果您的 code/plugins 是为早于 1.9 的 jQuery 版本开发的,请考虑使用 jQuery Migrate