DNS Prefetching is a performance optimization technique that reduces latency when users access websites by resolving domain names in advance. Browsers and modern applications widely use this technology to improve user experience.
Why DNS Prefetching is Needed
Latency with Traditional DNS Resolution
shellUser clicks link ↓ Browser initiates DNS query ↓ DNS resolution completes (20-100ms) ↓ Establish TCP connection ↓ Start loading page
Problems:
- DNS queries add to page load latency
- User wait time increases
- Affects user experience
Advantages of DNS Prefetching
shellPage loading ↓ Background prefetch of potentially accessed domains ↓ When user clicks ↓ DNS already resolved, establish connection directly ↓ Page loads faster
Advantages:
- Reduces page load latency
- Improves user experience
- Hides DNS query time
DNS Prefetching Implementation Methods
1. HTML Prefetching Tags
dns-prefetch
html<!DOCTYPE html> <html> <head> <!-- Prefetch CDN domain --> <link rel="dns-prefetch" href="//cdn.example.com"> <!-- Prefetch image domain --> <link rel="dns-prefetch" href="//img.example.com"> <!-- Prefetch API domain --> <link rel="dns-prefetch" href="//api.example.com"> </head> <body> <!-- Page content --> </body> </html>
preconnect
html<!DOCTYPE html> <html> <head> <!-- Preconnect (includes DNS resolution + TCP handshake) --> <link rel="preconnect" href="//cdn.example.com"> <link rel="preconnect" href="//api.example.com"> </head> <body> <!-- Page content --> </body> </html>
dns-prefetch vs preconnect:
| Feature | dns-prefetch | preconnect |
|---|---|---|
| Function | DNS resolution only | DNS + TCP + TLS |
| Resource Consumption | Low | Medium |
| Use Case | Potentially accessed resources | Definitely accessed resources |
2. Browser Automatic Prefetching
How It Works
When parsing HTML, browsers automatically discover links and resources in the page and resolve these domain names in advance.
html<!-- Browser automatically prefetches these domains --> <a href="https://www.example.com">Link</a> <img src="https://img.example.com/image.jpg"> <script src="https://cdn.example.com/script.js">
Browser Support
| Browser | Support | Notes |
|---|---|---|
| Chrome | ✅ Supported | Automatic prefetching |
| Firefox | ✅ Supported | Automatic prefetching |
| Safari | ✅ Supported | Automatic prefetching |
| Edge | ✅ Supported | Automatic prefetching |
3. HTTP Header Prefetching
Link Header
httpHTTP/1.1 200 OK Content-Type: text/html Link: <//cdn.example.com>; rel=dns-prefetch Link: <//api.example.com>; rel=preconnect
Server Configuration
nginxlocation / { add_header Link '<//cdn.example.com>; rel=dns-prefetch'; add_header Link '<//api.example.com>; rel=preconnect'; }
4. JavaScript Prefetching
Using Image Hack
javascript// Create hidden Image element to trigger DNS resolution function prefetchDNS(hostname) { const img = new Image(); img.src = '//' + hostname + '/favicon.ico?' + Date.now(); } // Prefetch multiple domains prefetchDNS('cdn.example.com'); prefetchDNS('api.example.com'); prefetchDNS('img.example.com');
Using Fetch API
javascript// Use Fetch API to trigger DNS resolution async function prefetchDNS(hostname) { try { await fetch('//' + hostname, { mode: 'no-cors' }); } catch (e) { // Ignore errors, just trigger DNS resolution } } prefetchDNS('cdn.example.com');
DNS Prefetching Best Practices
1. Prefetch Critical Resources
html<!-- Prefetch CDN --> <link rel="dns-prefetch" href="//cdn.example.com"> <!-- Prefetch API --> <link rel="dns-prefetch" href="//api.example.com"> <!-- Prefetch static resources --> <link rel="dns-prefetch" href="//static.example.com">
2. Reasonable Use of Prefetching
Priority Order:
- Above-the-fold Resources: CSS, critical JS
- CDN Domains: Static resource CDNs
- API Domains: Data interfaces
- Third-party Services: Analytics, ads, etc.
3. Avoid Over-prefetching
html<!-- ❌ Over-prefetching, wastes resources --> <link rel="dns-prefetch" href="//a.example.com"> <link rel="dns-prefetch" href="//b.example.com"> <link rel="dns-prefetch" href="//c.example.com"> <!-- ... 100 prefetches --> <!-- ✅ Reasonable prefetching, only critical domains --> <link rel="dns-prefetch" href="//cdn.example.com"> <link rel="dns-prefetch" href="//api.example.com">
4. Combine with Other Optimizations
html<!DOCTYPE html> <html> <head> <!-- DNS prefetching --> <link rel="dns-prefetch" href="//cdn.example.com"> <!-- Preconnect (DNS + TCP + TLS) --> <link rel="preconnect" href="//api.example.com"> <!-- Preload resources --> <link rel="preload" href="/styles.css" as="style"> <link rel="preload" href="/script.js" as="script"> </head> <body> <!-- Page content --> </body> </html>
Performance Impact Analysis
Performance Improvement with DNS Prefetching
| Scenario | Without Prefetching | With Prefetching | Improvement |
|---|---|---|---|
| First Visit | 100ms | 0ms | 100ms |
| Second Visit | 0ms (cached) | 0ms (cached) | 0ms |
| Cross-domain Resources | 80ms | 10ms | 70ms |
Resource Consumption
| Resource Type | Consumption | Description |
|---|---|---|
| Network Bandwidth | Low | Only DNS queries |
| DNS Server Load | Low | Few extra queries |
| Browser Memory | Low | Cache DNS results |
Monitoring and Testing
Testing DNS Prefetching
javascript// Test DNS prefetching effect const start = performance.now(); fetch('https://cdn.example.com/test.js') .then(() => { const end = performance.now(); console.log(`DNS resolution time: ${end - start}ms`); });
Monitoring Tools
- Chrome DevTools: Network panel to view DNS query times
- WebPageTest: Analyze DNS prefetching effects
- Lighthouse: Performance scores and recommendations
Common Interview Questions
Q: What's the difference between dns-prefetch and preconnect?
A:
- dns-prefetch: Only triggers DNS resolution, low resource consumption
- preconnect: Triggers DNS resolution + TCP handshake + TLS handshake, higher resource consumption but faster connection establishment
Q: Does DNS prefetching affect performance?
A:
- Positive Impact: Reduces page load latency, improves user experience
- Negative Impact: Few extra DNS queries, increases DNS server load
- Conclusion: Reasonable use of prefetching, performance improvement far outweighs extra overhead
Q: When should DNS prefetching be used?
A:
- Above-the-fold Resources: CSS, critical JS domains
- CDN Domains: Static resource CDNs
- API Domains: Data interface domains
- Third-party Services: Third-party services that will definitely be used
Q: Do browsers automatically prefetch?
A:
- Yes. Modern browsers (Chrome, Firefox, Safari, Edge) automatically prefetch domains discovered in the page
- But manual prefetching allows more precise control over timing and scope of prefetching
Summary
| Aspect | Description |
|---|---|
| Core Function | Resolve domain names in advance, reduce latency |
| Implementation Methods | HTML tags, browser automatic, HTTP headers, JavaScript |
| Key Tags | dns-prefetch, preconnect |
| Best Practices | Prefetch critical resources, avoid over-prefetching |
| Performance Improvement | Reduce 50-100ms page load latency |
| Resource Consumption | Low, few DNS queries |