乐闻世界logo
搜索文章和话题

What is DNS Prefetching and How to Implement DNS Prefetching

3月7日 12:08

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

shell
User 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

shell
Page 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:

Featuredns-prefetchpreconnect
FunctionDNS resolution onlyDNS + TCP + TLS
Resource ConsumptionLowMedium
Use CasePotentially accessed resourcesDefinitely 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

BrowserSupportNotes
Chrome✅ SupportedAutomatic prefetching
Firefox✅ SupportedAutomatic prefetching
Safari✅ SupportedAutomatic prefetching
Edge✅ SupportedAutomatic prefetching

3. HTTP Header Prefetching

http
HTTP/1.1 200 OK Content-Type: text/html Link: <//cdn.example.com>; rel=dns-prefetch Link: <//api.example.com>; rel=preconnect

Server Configuration

nginx
location / { 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:

  1. Above-the-fold Resources: CSS, critical JS
  2. CDN Domains: Static resource CDNs
  3. API Domains: Data interfaces
  4. 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

ScenarioWithout PrefetchingWith PrefetchingImprovement
First Visit100ms0ms100ms
Second Visit0ms (cached)0ms (cached)0ms
Cross-domain Resources80ms10ms70ms

Resource Consumption

Resource TypeConsumptionDescription
Network BandwidthLowOnly DNS queries
DNS Server LoadLowFew extra queries
Browser MemoryLowCache 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:

  1. Above-the-fold Resources: CSS, critical JS domains
  2. CDN Domains: Static resource CDNs
  3. API Domains: Data interface domains
  4. 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

AspectDescription
Core FunctionResolve domain names in advance, reduce latency
Implementation MethodsHTML tags, browser automatic, HTTP headers, JavaScript
Key Tagsdns-prefetch, preconnect
Best PracticesPrefetch critical resources, avoid over-prefetching
Performance ImprovementReduce 50-100ms page load latency
Resource ConsumptionLow, few DNS queries

标签:DNS