函数文档

wp_print_speculation_rules()

💡 云策文档标注

概述

wp_print_speculation_rules() 函数用于打印推测规则,以支持浏览器的预加载功能。它通过 wp_get_speculation_rules() 获取规则数据,并使用 wp_print_inline_script_tag() 输出为内联脚本标签。

关键要点

  • 函数 wp_print_speculation_rules() 在 WordPress 6.8.0 版本中引入,用于处理推测规则。
  • 它调用 wp_get_speculation_rules() 获取规则数据,如果数据为空则直接返回。
  • 使用 wp_print_inline_script_tag() 将规则数据编码为 JSON 并输出为 script[type="speculationrules"] 标签。
  • 对于不支持推测规则的浏览器,该标签会被忽略,确保向后兼容性。

代码示例

function wp_print_speculation_rules(): void {
    $speculation_rules = wp_get_speculation_rules();
    if ( null === $speculation_rules ) {
        return;
    }

    wp_print_inline_script_tag(
        (string) wp_json_encode(
            $speculation_rules,
            JSON_HEX_TAG | JSON_UNESCAPED_SLASHES
        ),
        array( 'type' => 'speculationrules' )
    );
}

注意事项

  • 该函数依赖于 wp_get_speculation_rules() 来获取规则配置,开发者需确保相关配置已正确设置。
  • 使用 JSON_HEX_TAG 和 JSON_UNESCAPED_SLASHES 选项进行 JSON 编码,以提高安全性和效率。
  • 输出标签的 type 属性设置为 "speculationrules",这是浏览器识别推测规则的标准方式。

📄 原文内容

Prints the speculation rules.

Description

For browsers that do not support speculation rules yet, the script[type="speculationrules"] tag will be ignored.

Source

function wp_print_speculation_rules(): void {
	$speculation_rules = wp_get_speculation_rules();
	if ( null === $speculation_rules ) {
		return;
	}

	wp_print_inline_script_tag(
		(string) wp_json_encode(
			$speculation_rules,
			JSON_HEX_TAG | JSON_UNESCAPED_SLASHES
		),
		array( 'type' => 'speculationrules' )
	);
}

Changelog

Version Description
6.8.0 Introduced.