钩子文档

script_loader_tag

💡 云策文档标注

概述

script_loader_tag 是一个 WordPress 过滤器,用于修改已入队脚本的 HTML script 标签。它允许开发者自定义脚本标签的属性,如添加 defer 或 async 属性,以优化页面加载性能。

关键要点

  • script_loader_tag 过滤器可以修改 script 标签的 HTML 输出,常用于添加 defer 或 async 属性。
  • 过滤器接受参数 $tag(脚本标签字符串)和 $handle(脚本句柄),支持基于句柄进行条件过滤。
  • 使用此过滤器时,应确保脚本通过 wp_enqueue_script() 正确注册和入队,以避免编码标准错误。
  • 可以排除特定脚本句柄(如 'jquery'、'wp-i18n')以避免影响核心功能。

代码示例

function prefix_defer_js($tag, $handle) {
    if (is_admin()) return $tag;
    $exclude_handles = [
        'heartbeat',
        'wp-hooks',
        'wp-auth-check',
        'jquery',
        'jquery-core',
        'jquery-ui-core',
        'wp-i18n'
    ];
    if (in_array($handle, $exclude_handles)) {
        return $tag;
    } else {
        return str_replace('>', ' defer>', $tag);
    }
}
add_filter('script_loader_tag', 'prefix_defer_js', 10, 2);

注意事项

  • 避免对所有脚本应用 defer 或 async,某些核心脚本(如 jQuery)可能需要立即执行。
  • 确保使用 wp_enqueue_script() 注册脚本,以符合 WordPress 编码标准。
  • 在非管理员页面应用过滤器,以避免影响后台功能。

📄 原文内容

Filters the HTML script tag of an enqueued script.

Parameters

$tagstring
The <script> tag for the enqueued script.
$handlestring
The script’s registered handle.
$srcstring
The script’s source URL.

Source

$tag = apply_filters( 'script_loader_tag', $tag, $handle, $src );

Changelog

Version Description
4.1.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Useful when a script excecution depends on “ attributes, eg:

    add_filter( 'script_loader_tag', 'add_id_to_script', 10, 3 );
    
    function add_id_to_script( $tag, $handle, $src ) {
        if ( 'dropbox.js' === $handle ) {
            $tag = '<script type="text/javascript" src="' . esc_url( $src ) . '" id="dropboxjs" data-app-key="MY_APP_KEY"></script>';
        }
    
        return $tag;
    }

  2. Skip to note 4 content

    It can be used to defer or async all JS scripts :

    function prefix_defer_js( $html ) {
        if ( ! is_admin() ) {
            $html = str_replace( '></script>', ' defer></script>', $html );
        }
        return $html;
    }
    add_filter( 'script_loader_tag', 'prefix_defer_js' );

    You can also use the $handle argument to filter scripts.