wp_scripts_get_suffix()
云策文档标注
概述
wp_scripts_get_suffix() 函数用于获取脚本文件的后缀,支持普通后缀和开发后缀两种类型。它根据 SCRIPT_DEBUG 常量和 WordPress 版本中的 '-src' 字符串动态生成后缀。
关键要点
- 函数返回脚本后缀字符串,用于区分开发和生产环境下的脚本文件。
- 支持两种后缀类型:普通后缀(默认)和开发后缀(通过参数 'dev' 指定)。
- 后缀生成逻辑基于 SCRIPT_DEBUG 常量:若为 true 则返回空字符串(无后缀),否则返回 '.min'。
- 开发后缀还额外检查 WordPress 版本是否包含 '-src' 字符串,以确定是否为开发版本。
- 函数内部使用静态变量缓存后缀数组,避免重复计算。
代码示例
function wp_scripts_get_suffix( $type = '' ) {
static $suffixes;
if ( null === $suffixes ) {
require ABSPATH . WPINC . '/version.php';
$develop_src = false !== strpos( $wp_version, '-src' );
if ( ! defined( 'SCRIPT_DEBUG' ) ) {
define( 'SCRIPT_DEBUG', $develop_src );
}
$suffix = SCRIPT_DEBUG ? '' : '.min';
$dev_suffix = $develop_src ? '' : '.min';
$suffixes = array(
'suffix' => $suffix,
'dev_suffix' => $dev_suffix,
);
}
if ( 'dev' === $type ) {
return $suffixes['dev_suffix'];
}
return $suffixes['suffix'];
}注意事项
- 函数在首次调用时定义 SCRIPT_DEBUG 常量(如果未定义),基于 WordPress 版本是否包含 '-src'。
- 注意兼容性:代码中避免使用 str_contains() 函数,以确保在特定加载场景(如 wp-admin/load-scripts.php)下正常工作。
- 后缀缓存机制提高了性能,但开发者需了解其静态变量特性。
原文内容
Returns the suffix that can be used for the scripts.
Description
There are two suffix types, the normal one and the dev suffix.
Parameters
$typestringrequired-
The type of suffix to retrieve.
Source
function wp_scripts_get_suffix( $type = '' ) {
static $suffixes;
if ( null === $suffixes ) {
/*
* Include an unmodified $wp_version.
*
* Note: wp_get_wp_version() is not used here, as this file can be included
* via wp-admin/load-scripts.php or wp-admin/load-styles.php, in which case
* wp-includes/functions.php is not loaded.
*/
require ABSPATH . WPINC . '/version.php';
/*
* Note: str_contains() is not used here, as this file can be included
* via wp-admin/load-scripts.php or wp-admin/load-styles.php, in which case
* the polyfills from wp-includes/compat.php are not loaded.
*/
$develop_src = false !== strpos( $wp_version, '-src' );
if ( ! defined( 'SCRIPT_DEBUG' ) ) {
define( 'SCRIPT_DEBUG', $develop_src );
}
$suffix = SCRIPT_DEBUG ? '' : '.min';
$dev_suffix = $develop_src ? '' : '.min';
$suffixes = array(
'suffix' => $suffix,
'dev_suffix' => $dev_suffix,
);
}
if ( 'dev' === $type ) {
return $suffixes['dev_suffix'];
}
return $suffixes['suffix'];
}
Changelog
| Version | Description |
|---|---|
| 5.0.0 | Introduced. |