Skip to content

Commit 71ee270

Browse files
author
George Stephanis
committed
Add function to Jetpack to centralize DNS Prefetch
And unit tests.
1 parent c01db67 commit 71ee270

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

class.jetpack.php

+23
Original file line numberDiff line numberDiff line change
@@ -4930,4 +4930,27 @@ function concat_remove_style_loader_tag( $tag, $handle ) {
49304930

49314931
return $tag;
49324932
}
4933+
4934+
/**
4935+
* Stores and prints out domains to prefetch for page speed optimization.
4936+
*
4937+
* @param mixed $new_urls
4938+
*/
4939+
public static function dns_prefetch( $new_urls = null ) {
4940+
static $prefetch_urls = array();
4941+
if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
4942+
echo "\r\n";
4943+
foreach ( $prefetch_urls as $this_prefetch_url ) {
4944+
printf( "<link rel='dns-prefetch' href='%s'>\r\n", esc_attr( $this_prefetch_url ) );
4945+
}
4946+
} elseif ( ! empty( $new_urls ) ) {
4947+
if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
4948+
add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
4949+
}
4950+
foreach ( (array) $new_urls as $this_new_url ) {
4951+
$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
4952+
}
4953+
$prefetch_urls = array_unique( $prefetch_urls );
4954+
}
4955+
}
49334956
}

tests/test_class.jetpack.php

+26
Original file line numberDiff line numberDiff line change
@@ -280,4 +280,30 @@ public function test_implode_frontend_css_does_not_enqueue_bundle_when_disabled_
280280

281281
$this->assertTrue( $seen_orig );
282282
}
283+
284+
/**
285+
* @author georgestephanis
286+
* @covers Jetpack::dns_prefetch
287+
* @since 3.3.0
288+
*/
289+
public function test_dns_prefetch() {
290+
// Purge it for a clean start.
291+
ob_start();
292+
Jetpack::dns_prefetch();
293+
ob_clean();
294+
295+
Jetpack::dns_prefetch( 'http://example1.com/' );
296+
Jetpack::dns_prefetch( array(
297+
'http://example2.com/',
298+
'https://example3.com',
299+
) );
300+
Jetpack::dns_prefetch( 'https://example2.com' );
301+
302+
$expected = "\r\n" .
303+
"<link rel='dns-prefetch' href='//example1.com'>\r\n" .
304+
"<link rel='dns-prefetch' href='//example2.com'>\r\n" .
305+
"<link rel='dns-prefetch' href='//example3.com'>\r\n";
306+
307+
$this->assertEquals( $expected, get_echo( array( 'Jetpack', 'dns_prefetch' ) ) );
308+
}
283309
} // end class

0 commit comments

Comments
 (0)