wp_register_script_module()
云策文档标注
概述
wp_register_script_module() 函数用于注册一个脚本模块,前提是该脚本模块标识符尚未被注册。它是 WordPress 脚本模块系统的核心函数,支持依赖管理、版本控制和额外参数配置。
关键要点
- 函数签名:wp_register_script_module( string $id, string $src, array $deps = array(), $version = false, array $args = array() )
- 参数说明:$id 为唯一标识符;$src 为脚本模块的 URL 或路径;$deps 为依赖数组,支持静态或动态导入;$version 用于缓存控制;$args 包含 in_footer 和 fetchpriority 等额外选项。
- 依赖处理:依赖可以是字符串或数组,数组需包含 id 键和可选的 import 键(static 或 dynamic)。
- 版本控制:$version 默认为 false,使用 WordPress 版本;null 表示不添加版本;字符串用于自定义版本号。
- 内部调用:函数通过 wp_script_modules()->register() 实现注册逻辑。
- 相关函数:与 WP_Script_Modules::register()、wp_script_modules()、wp_default_script_modules() 和 register_block_script_module_id() 关联。
- 变更历史:在 WordPress 6.5.0 引入,6.9.0 添加了 $args 参数。
代码示例
wp_register_script_module(
'my-module',
get_template_directory_uri() . '/js/my-module.js',
array( 'dependency-module' ),
'1.0.0',
array( 'in_footer' => true, 'fetchpriority' => 'high' )
);注意事项
- 确保 $id 唯一,以避免重复注册。
- 依赖数组中的 import 键默认为 static,动态导入需显式指定。
- $args 参数仅适用于块主题,例如 in_footer 控制脚本模块在页脚打印。
原文内容
Registers the script module if no script module with that script module identifier has already been registered.
Parameters
$idstringrequired- The identifier of the script module. Should be unique. It will be used in the final import map.
$srcstringoptional- Full URL of the script module, or path of the script module relative to the WordPress root directory. If it is provided and the script module has not been registered yet, it will be registered.
$depsarrayoptional- List of dependencies.
...$0string|arrayAn array of script module identifiers of the dependencies of this script module. The dependencies can be strings or arrays. If they are arrays, they need anidkey with the script module identifier, and can contain animportkey with eitherstaticordynamic. By default, dependencies that don’t contain animportkey are considered static.idstringThe script module identifier.importstringOptional. Import type. May be eitherstaticordynamic. Defaults tostatic.
Default:
array()$versionstring|false|nulloptionalString specifying the script module version number. Defaults to false.
It is added to the URL as a query string for cache busting purposes. If $version is set to false, the version number is the currently installed WordPress version.
If $version is set to null, no version is added.Default:
false$argsarrayoptionalAn array of additional args.
in_footerboolWhether to print the script module in the footer. Only relevant to block themes. Default'false'. Optional.fetchpriority‘auto’|’low’|’high’Fetch priority. Default'auto'. Optional.
Default:
array()Source
function wp_register_script_module( string $id, string $src, array $deps = array(), $version = false, array $args = array() ) { wp_script_modules()->register( $id, $src, $deps, $version, $args ); }Changelog
User Contributed Notes
You must log in before being able to contribute a note or feedback.