When a browser requests a resource from a cross-origin (third party) server, that cross-origin’s domain name must be resolved to an IP address before the browser can issue the request. This process is known as DNS resolution. While DNS caching can help to reduce this latency, DNS resolution can add significant latency to requests. For websites that open connections to many third parties, this latency can significantly reduce loading performance.
dns-prefetch helps developers mask DNS resolution latency. The HTML
<link> element offers this functionality by way of a
rel attribute value of
dns-prefetch. The cross-origin domain is then specified in the href attribute:
<link rel="dns-prefetch" href="https://fonts.googleapis.com/">
You should place dns-prefetch hints in the
<head> element any time your site references resources on cross-origin domains, but there are some things to keep in mind. For one,
dns-prefetch is only effective for DNS lookups on cross-origin domains, so avoid using it for your site. This is because the IP behind your site’s domain will have already been resolved by the time the browser sees the hint.
Second, it’s also possible to specify dns-prefetch (and other resources hints) as an HTTP header:
Link: <https://fonts.googleapis.com/>; rel=dns-prefetch
Third, consider pairing
dns-prefetch with the
preconnect hint. While
dns-prefetch only performs a DNS lookup, preconnect establishes a connection to a server. This process includes DNS resolution, as well as establishing the TCP connection, and performing the TLS handshake—if a site is served over HTTPS. Combining the two provides an opportunity to further reduce the perceived latency of cross-origin requests. You can safely use them together like so:
<link rel="preconnect" href="https://fonts.googleapis.com/" crossorigin> <link rel="dns-prefetch" href="https://fonts.googleapis.com/">
The logic behind pairing these hints is because support for dns-prefetch is better than support for preconnect. Browsers that don’t support preconnect will still get some added benefit by falling back to dns-prefetch.
Because this is an HTML feature, it is very fault-tolerant. If a non-supporting browser encounters a dns-prefetch hint—or any other resource hint—your site won’t break. You just won’t receive the benefits it provides.