Resource Hints: Allow passing custom attributes to resource hints.

[37920] introduced resource hints that allow browsers to prefetch specific pages or render them in the background. With this change, the `as`, `crossorigin`, `pr`, and `type` attributes can be passed in addition to the URLs/hosts.

Props peterwilsoncc, swissspidy.
Fixes #38121.
Built from https://develop.svn.wordpress.org/trunk@38826


git-svn-id: http://core.svn.wordpress.org/trunk@38769 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
Pascal Birchler 2016-10-19 09:29:30 +00:00
parent 39433ad092
commit deda5d9796
2 changed files with 45 additions and 7 deletions

View File

@ -2830,6 +2830,8 @@ function wp_resource_hints() {
$hints['dns-prefetch'][] = apply_filters( 'emoji_svg_url', 'https://s.w.org/images/core/emoji/2.2.1/svg/' );
foreach ( $hints as $relation_type => $urls ) {
$unique_urls = array();
/**
* Filters domains and URLs for resource hints of relation type.
*
@ -2841,16 +2843,31 @@ function wp_resource_hints() {
$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 ) {
unset( $urls[ $key ] );
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'] ) ) {
unset( $urls[ $key ] );
continue;
}
@ -2862,13 +2879,34 @@ function wp_resource_hints() {
}
}
$urls[ $key ] = $url;
$atts['rel'] = $relation_type;
$atts['href'] = $url;
$unique_urls[ $url ] = $atts;
}
$urls = array_unique( $urls );
foreach ( $unique_urls as $atts ) {
$html = '';
foreach ( $urls as $url ) {
printf( "<link rel='%s' href='%s' />\n", $relation_type, $url );
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";
}
}
}

View File

@ -4,7 +4,7 @@
*
* @global string $wp_version
*/
$wp_version = '4.7-alpha-38825';
$wp_version = '4.7-alpha-38826';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.