+/**
+ * Prints resource hints to browsers for pre-fetching, pre-rendering
+ * and pre-connecting to web sites.
+ *
+ * Gives hints to browsers to prefetch specific pages or render them
+ * in the background, to perform DNS lookups or to begin the connection
+ * handshake (DNS, TCP, TLS) in the background.
+ *
+ * These performance improving indicators work by using `<link rel"…">`.
+ *
+ * @since 4.6.0
+ */
+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/2/svg/' );
+
+ foreach ( $hints as $relation_type => $urls ) {
+ /**
+ * 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 ) {
+ $url = esc_url( $url, array( 'http', 'https' ) );
+ if ( ! $url ) {
+ unset( $urls[ $key ] );
+ continue;
+ }
+
+ if ( in_array( $relation_type, array( 'preconnect', 'dns-prefetch' ) ) ) {
+ $parsed = wp_parse_url( $url );
+ if ( empty( $parsed['host'] ) ) {
+ unset( $urls[ $key ] );
+ 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'];
+ }
+ }
+
+ $urls[ $key ] = $url;
+ }
+
+ $urls = array_unique( $urls );
+
+ foreach ( $urls as $url ) {
+ printf( "<link rel='%s' href='%s'>\n", $relation_type, $url );
+ }
+ }
+}
+
+/**
+ * Retrieves a list of unique hosts of all enqueued scripts and styles.
+ *
+ * @since 4.6.0
+ *
+ * @return array A list of unique hosts of enqueued scripts and styles.
+ */
+function wp_dependencies_unique_hosts() {
+ global $wp_scripts, $wp_styles;
+
+ $unique_hosts = array();
+
+ foreach ( array( $wp_scripts, $wp_styles ) as $dependencies ) {
+ if ( $dependencies instanceof WP_Dependencies && ! empty( $dependencies->queue ) ) {
+ foreach ( $dependencies->queue as $handle ) {
+ if ( ! isset( $dependencies->registered[ $handle ] ) ) {
+ continue;
+ }
+
+ /* @var _WP_Dependency $dependency */
+ $dependency = $dependencies->registered[ $handle ];
+ $parsed = wp_parse_url( $dependency->src );
+
+ if ( ! empty( $parsed['host'] ) && ! in_array( $parsed['host'], $unique_hosts ) && $parsed['host'] !== $_SERVER['SERVER_NAME'] ) {
+ $unique_hosts[] = $parsed['host'];
+ }
+ }
+ }
+ }
+
+ return $unique_hosts;
+}
+