函数文档

wp_script_add_data()

💡 云策文档标注

概述

wp_script_add_data() 函数用于向已注册的脚本添加元数据,如策略属性或条件注释。它依赖于脚本已注册,并返回操作成功与否的布尔值。

关键要点

  • 函数作用:向脚本添加元数据,例如 'strategy' 值('defer' 或 'async')或条件注释。
  • 前提条件:脚本必须已通过 wp_enqueue_script() 注册,否则函数无效。
  • 参数:$handle(脚本句柄,字符串,必需)、$key(数据键名,字符串,必需)、$value(数据值,混合类型,必需)。
  • 返回值:成功返回 true,失败返回 false。
  • 内部实现:调用 wp_scripts()->add_data() 方法,继承自 WP_Dependencies 类。
  • 版本变更:WordPress 6.9.0 更新了可能的值,移除了 'conditional' 引用并添加了 'strategy'。

代码示例

// 添加 async 属性到脚本
function twentytwenty_register_scripts() {
    wp_enqueue_script( 'twentytwenty-js', get_template_directory_uri() . '/assets/js/index.js', array(), '1.0', false );
    wp_script_add_data( 'twentytwenty-js', 'async', true );
}
add_action( 'wp_enqueue_scripts', 'twentytwenty_register_scripts' );

注意事项

  • 确保脚本已注册后再调用此函数,否则元数据添加会失败。
  • 在 WordPress 6.9.0 及以上版本中,推荐使用 'strategy' 键名来设置 'defer' 或 'async' 值,而非旧版的 'conditional'。
  • 函数主要用于控制脚本加载行为,如异步或延迟执行,或针对特定浏览器条件加载。

📄 原文内容

Adds metadata to a script.

Description

Works only if the script has already been registered.

Possible values for $key and $value: ‘strategy’ string ‘defer’ or ‘async’.

See also

Parameters

$handlestringrequired
Name of the script.
$keystringrequired
Name of data point for which we’re storing a value.
$valuemixedrequired
String containing the data to be added.

Return

bool True on success, false on failure.

Source

function wp_script_add_data( $handle, $key, $value ) {
	return wp_scripts()->add_data( $handle, $key, $value );
}

Changelog

Version Description
6.9.0 Updated possible values to remove reference to 'conditional' and add 'strategy'.
4.2.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Enqueue IE-specific Scripts with conditional comments

    function wpdemo_enqueue_scripts() {
        wp_enqueue_script( 'wpdemo-respond', get_template_directory_uri().'/js/respond.min.js' );
        wp_script_add_data( 'wpdemo-respond', 'conditional', 'lt IE 9' );
    
        wp_enqueue_script( 'wpdemo-html5shiv',get_template_directory_uri().'/js/html5shiv.js');
        wp_script_add_data( 'wpdemo-html5shiv', 'conditional', 'lt IE 9' );
    }
    add_action( 'wp_enqueue_scripts', 'wpdemo_enqueue_scripts' );

  2. Skip to note 4 content

    Add IE-specific CDN Scripts with conditional comments

    function add_scripts_for_IE() {
    	wp_enqueue_script( 'html5shiv.min.js', '//oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js' );
    	wp_script_add_data( 'html5shiv.min.js', 'conditional', 'lt IE 9' );
    
    	wp_enqueue_script( 'respond.min.js',  '//oss.maxcdn.com/respond/1.4.2/respond.min.js' );
    	wp_script_add_data( 'respond.min.js', 'conditional', 'lt IE 9' );
    }
    add_action( 'wp_enqueue_scripts', 'add_scripts_for_IE' );