向 WordPress 发送 Link 头部,以实现脚本和样式的 HTTP/2 服务器推送。

安装次数: 12,883

依赖项: 0

建议者: 0

安全性: 0

星标: 5

关注者: 3

分支: 0

开放问题: 6

类型:wordpress-plugin

2.2.0 2022-11-08 15:19 UTC

README

PHPUnit Tests Coding Standards

向 WordPress 发送 Link 头部,以实现脚本和样式的 HTTP/2 服务器推送。如果已经发送了头部,则回退到 <link> 元素。
提供过滤器以自定义和扩展要推送的资源。

Screenshot

安装

使用以下命令安装最新版本:

composer require wearerequired/h2push

该插件至少需要 PHP 7.4 和 WordPress 5.6。

钩子参考

h2push.as_header

默认情况下,如果尚未发送任何头部,则插件将使用 Link 头部,并回退到 <link> 元素。要更改此行为,您可以使用 h2push.as_header 过滤器。示例

// Force H2 Push to always use the `<link>` element.
add_filter( 'h2push.as_header', '__return_false' );

此过滤器也适用于服务器尚不支持 HTTP/2 但您仍想从预加载中受益的情况。

h2push.push_resources

默认情况下,插件会收集在 wp_enqueue_scripts 钩子之前或之前注册的所有已排队的脚本和样式。 h2push.push_resources 过滤器允许自定义资源列表。示例

/**
 * Add web font and hero image to the list of resources to push/preload.
 *
 * @param array $resources List of resources.
 * @return array List of resources.
 */
function my_theme_push_resources( array $resources ): array {
	$relative_template_directory_uri = wp_parse_url( get_template_directory_uri(), PHP_URL_PATH );

	// Push web font.
	$resources[] = [
		'href' => $relative_template_directory_uri . '/assets/fonts/fancy.woff2',
		'as'   => 'font',
		'type' => 'font/woff2',
		'crossorigin',
	];

	if ( is_front_page() && ! is_paged() ) {
		// Push hero image.
		$resources[] = [
			'href' => $relative_template_directory_uri . '/assets/images/hero.webp',
			'as'   => 'image',
			'type' => 'image/webp',
		];
	}

	return $resources;
}
add_filter( 'h2push.push_resources', 'my_theme_push_resources' );

h2push.is_allowed_push_host

默认情况下,插件只为本地资源发送推送请求,其中资产 URL 与主页 URL 匹配。要更改此行为,您可以使用 h2push.is_allowed_push_host 过滤器。示例

/**
 * Allow resources from example.org to be pushed/preloaded too.
 *
 * @param bool   $is_allowed Whether the host should be allowed. Default true for local resources.
 * @param string $host       The host name of the resource.
 * @return bool Whether the host should be allowed.
 */
function my_theme_is_allowed_push_host( $is_allowed, $host ) {
	return $is_allowed || 'example.org' === $host;
}
add_filter( 'h2push.is_allowed_push_host', 'my_theme_is_allowed_push_host' );