What is DNS Prefetch and why you should implement it on your website

We previously talked about what Preconnect is and why you should implement it on your website. In this occasion we will talk about DNS Prefetch, a similar technique.

What is DNS Prefetch?

You probably know that domains exist just so we don’t have to remember the IPs of the servers of every website. Resolving a domain to an IP address is a process that takes some time, usually around 20-120ms, and that is done for every external domain that your website includes. Wouldn’t it be nice if these connections were made in the background while your page is loading, so when the actual resources need to be downloaded it all would take less time? That’s what DNS Prefetch does.

DNS Prefetch tells the browser to look up the domain name and resolve it to an IP address as soon as possible in the background, while all the rest of resources of your page are loading. To illustrate this, let’s do a simple test.

Without DNS Prefetch

The previous screenshots shows a test site with a few external connections without doing DNS Prefetch. And here’s with DNS Prefetch:

With DNS Prefetch

Do you see those little turquoise bars before each connection? That’s the time it takes to look up the domain name, and if DNS Prefetch is not in place, it makes the connection to the external domain take longer, you can compare the two screenshots. So by implementing DNS Prefetch, we are doing some work on the background while the page is loading that helps us save some time.

How to implement DNS Prefetch?

Following the previous example, the goal is to enter the following lines between the tags <head> and </head> of the site.

<link rel="dns-prefetch" href="//www.chphotography.co.uk">
<link rel="dns-prefetch" href="//connect.facebook.net">
<link rel="dns-prefetch" href="//www.facebook.com">

Note: we did not add the connection to cdn.shortpixel.ai, because ShortPixel Adaptive Images, which is installed on the test site, already adds a preconnect rule, so there’s no need for a dns-prefetch.

To add those lines, we have two methods.

1 – Use a plugin like Insert Headers and Footers. Install, activate it, go to Settings and add the code in the first box.

2 – The recommended method, but for advanced users: Edit the functions.php file of your child theme and add the following piece of code.

function shortpixel_dnsprefetch() {
echo '<link rel="dns-prefetch" href="//www.chphotography.co.uk">
<link rel="dns-prefetch" href="//connect.facebook.net">
<link rel="dns-prefetch" href="//www.facebook.com">';
}
add_action('wp_head', 'shortpixel_dnsprefetch', 0);

Newsletter Updates

Enter your email address below and subscribe to our newsletter

Leave a Reply

Your email address will not be published. Required fields are marked *