向浏览器打印资源提示,以进行预取,预呈现和预连接到网站。

原型

wp_resource_hints()

描述

为浏览器提供提示以预取特定页面或在后台呈现它们,执行DNS查找或在后台开始连接握手(DNS,TCP,TLS)。

源文件

路径:wp-includes/general-template.php

<?php
...
function wp_resource_hints() {
	$hints = array(
		'dns-prefetch' => wp_dependencies_unique_hosts(),
		'preconnect'   => array(),
		'prefetch'     => array(),
		'prerender'    => array(),
	);
	/*
	 * Add DNS prefetch for the Emoji CDN.
	 * The path is removed in the foreach loop below.
	 */
	/** This filter is documented in wp-includes/formatting.php */
	$hints['dns-prefetch'][] = apply_filters( 'emoji_svg_url', 'https://s.w.org/images/core/emoji/11/svg/' );
	foreach ( $hints as $relation_type => $urls ) {
		$unique_urls = array();
		/**
		 * Filters domains and URLs for resource hints of relation type.
		 *
		 * @since 4.6.0
		 *
		 * @param array  $urls          URLs to print for resource hints.
		 * @param string $relation_type The relation type the URLs are printed for, e.g. 'preconnect' or 'prerender'.
		 */
		$urls = apply_filters( 'wp_resource_hints', $urls, $relation_type );
		foreach ( $urls as $key => $url ) {
			$atts = array();
			if ( is_array( $url ) ) {
				if ( isset( $url['href'] ) ) {
					$atts = $url;
					$url  = $url['href'];
				} else {
					continue;
				}
			}
			$url = esc_url( $url, array( 'http', 'https' ) );
			if ( ! $url ) {
				continue;
			}
			if ( isset( $unique_urls[ $url ] ) ) {
				continue;
			}
			if ( in_array( $relation_type, array( 'preconnect', 'dns-prefetch' ) ) ) {
				$parsed = wp_parse_url( $url );
				if ( empty( $parsed['host'] ) ) {
					continue;
				}
				if ( 'preconnect' === $relation_type && ! empty( $parsed['scheme'] ) ) {
					$url = $parsed['scheme'] . '://' . $parsed['host'];
				} else {
					// Use protocol-relative URLs for dns-prefetch or if scheme is missing.
					$url = '//' . $parsed['host'];
				}
			}
			$atts['rel'] = $relation_type;
			$atts['href'] = $url;
			$unique_urls[ $url ] = $atts;
		}
		foreach ( $unique_urls as $atts ) {
			$html = '';
			foreach ( $atts as $attr => $value ) {
				if ( ! is_scalar( $value ) ||
				     ( ! in_array( $attr, array( 'as', 'crossorigin', 'href', 'pr', 'rel', 'type' ), true ) && ! is_numeric( $attr ))
				) {
					continue;
				}
				$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
				if ( ! is_string( $attr ) ) {
					$html .= " $value";
				} else {
					$html .= " $attr='$value'";
				}
			}
			$html = trim( $html );
			echo "<link $html />n";
		}
	}
}
...
?>

其他

英文文档:https://developer.wordpress.org/reference/functions/wp_resource_hints/