DNS Prefetch for Performance Optimization
Use dns-prefetch to resolve domain names early for third-party resources, reducing DNS lookup latency and improving page load performance.
Detailed Explanation
DNS Prefetch for Performance
<link rel="dns-prefetch"> is the lightest resource hint available. It tells the browser to perform DNS resolution for a domain name in advance, so when the browser eventually needs a resource from that domain, the DNS lookup is already complete.
What DNS Resolution Costs
Every time the browser needs to contact a new domain, it must resolve the domain name to an IP address through the DNS system. This lookup typically takes:
- 20-50ms on fast connections with nearby DNS servers
- 100-200ms on mobile networks or with distant DNS servers
- 500ms+ when DNS servers are slow or when there are multiple CNAME redirections
For a page that references 10-20 different domains (scripts, analytics, ads, CDNs, fonts), DNS lookups alone can add 1-2 seconds to page load time.
Syntax and Usage
<!-- Resolve DNS for origins you'll need soon -->
<link rel="dns-prefetch" href="https://fonts.googleapis.com" />
<link rel="dns-prefetch" href="https://cdn.example.com" />
<link rel="dns-prefetch" href="https://api.example.com" />
<link rel="dns-prefetch" href="https://analytics.example.com" />
dns-prefetch vs preconnect
| Feature | dns-prefetch | preconnect |
|---|---|---|
| DNS resolution | Yes | Yes |
| TCP handshake | No | Yes |
| TLS negotiation | No | Yes |
| Resource cost | Very low | Moderate |
| Browser support | Very wide | Wide |
| Best for | Many origins, low priority | Few origins, high priority |
When to Use dns-prefetch
- Resources from origins you will need later in the page lifecycle (lazy-loaded images, deferred scripts)
- Origins from third-party embeds (social media widgets, comment systems)
- As a fallback alongside preconnect for older browsers
- When you have many origins (>4) and preconnecting to all would be wasteful
Combined Pattern
A common pattern uses both preconnect and dns-prefetch together:
<link rel="preconnect" href="https://fonts.gstatic.com"
crossorigin="anonymous" />
<link rel="dns-prefetch" href="https://fonts.gstatic.com" />
Browsers that support preconnect will ignore the dns-prefetch; older browsers will benefit from at least the DNS resolution.
Use Case
A blog that embeds tweets, YouTube videos, and loads third-party commenting systems adds dns-prefetch hints for each embed domain. Since these embeds are below the fold and loaded lazily, dns-prefetch is more appropriate than preconnect because it uses fewer resources while still saving DNS lookup time when the user scrolls.