问题描述

我不能在插件 javascripts 中添加延迟标记。 Google 开发人员的 pagepeed 测试建议我添加 defer 标签的联系方式 7 javascripts 。

这是接触表格 7 如何在标题中包含 JavaScript 。

add_action( 'wp_enqueue_scripts', 'wpcf7_enqueue_scripts' );

function wpcf7_enqueue_scripts() {
    // jquery.form.js originally bundled with WordPress is out of date and deprecated
    // so we need to deregister it and re-register the latest one
    wp_deregister_script( 'jquery-form' );
    wp_register_script( 'jquery-form', wpcf7_plugin_url( 'jquery.form.js' ),
        array( 'jquery' ), '2.52', true );

    $in_footer = true;
    if ( 'header' === WPCF7_LOAD_JS )
        $in_footer = false;

    wp_enqueue_script( 'contact-form-7', wpcf7_plugin_url( 'scripts.js' ),
        array( 'jquery', 'jquery-form' ), WPCF7_VERSION, $in_footer );

    do_action( 'wpcf7_enqueue_scripts' );
}

现在如何在上面的代码中添加 defer = “defer” 标签?

最佳解决方案

从 WordPress 4.1 起,有一个过滤器:script_loader_tag 。您可以使用它来查找正确的脚本:

add_filter( 'script_loader_tag', function ( $tag, $handle ) {

    if ( 'contact-form-7' !== $handle )
        return $tag;

    return str_replace( ' src', ' defer="defer" src', $tag );
}, 10, 2 );

老回答

没有专用的过滤器可用… 至少我看不到。但是…

  •  wp_print_scripts()调用 WP_Scripts->do_items()

  • 它调用 WP_Scripts->do_item()

  • 使用 esc_url()

  • 它提供了一个过滤器:'clean_url'

现在我们开始:

function add_defer_to_cf7( $url )
{
    if ( FALSE === strpos( $url, 'contact-form-7' )
      or FALSE === strpos( $url, '.js' )
    )
    { // not our file
        return $url;
    }
    // Must be a ', not "!
    return "$url' defer='defer";
}
add_filter( 'clean_url', 'add_defer_to_cf7', 11, 1 );

警告:没有测试,只是一个想法。 🙂

Update

我用这段代码编写和测试了一个插件。见 https://gist.github.com/1584783

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。