WP Munk > Blog > Code Snippets > How to add DNS Prefetch in a WordPress Theme without using Plugin

How to add DNS Prefetch in a WordPress Theme without using Plugin

Go to Google, search for any keyword, hold two seconds and then click the first link, that site will open instantly on your browser without showing you any loading progress.  That is called DNS Preftech.

Google defines it as:

DNS prefetching is an attempt to resolve domain names before a user tries to follow a link. This is done using the computer’s normal DNS resolution mechanism; no connection to Google is used.

So, basically what is happening is that your browser downloads and saves the URL in its buffer and as soon as you click that link it shows you the page from its buffer rather than pulling it from the server. As a developer you cannot know which link your user might click but on certain pages you can anticipate which link a user might click.

For an example, on a blog archive page – a user might click the first news whereas on the single post/page a user might click the home link or the logo to visit the homepage on your site. So, you can add DNS Prefetching for these links based on what you think your user might click next.  You can use the following code snippet and and paste it your theme’s functions.php to enable DNS Prefetching in single post .

if( ! function_exists( 'wphelp_dns_prefetch' ) ) :

	function wphelp_dns_prefetch(){
		
		if ( is_singular() ) { 
                  echo '<link rel="prefetch" href="' .esc_url( home_url() ) . '">';				
                   echo '<link rel="prerender" href="' .esc_url( home_url() ) . '">';				
		}

	}

endif;

add_action('wp_head', 'wphelp_dns_prefetch');

This snippet will enable DNS Prefetching on single post, so when a user is on single post or page or any custom post type and clicks on the link for homepage then the homepage will open without any delay.

Note: DNS Prefetching only works with HTTP2. So if your server does not supports HTTP2 then this will not work.

About The Author


Mohammad Tajim

Hello, I am Mohammad Tajim a WordPress Developer with over 14 years of experience building WP Products. I made Munk WordPress Theme and other themes available at metricthemes.com. Follow me on twitter @tajim