What is dns-prefetch in HTML and How to Use It
dns-prefetch link relation in HTML tells the browser to look up the IP address of a domain early, before a user clicks a link or loads a resource from that domain. This helps speed up loading times by resolving domain names in advance.How It Works
When you visit a website, your browser needs to find the IP address of any domain it wants to connect to. This process is called DNS lookup. Normally, the browser waits until it needs to load something from a domain before doing this lookup.
Using dns-prefetch is like telling your browser to do this lookup early, while the page is still loading. Imagine you are planning a trip and you look up the address of your hotel before you leave home. This way, when you arrive, you can go straight there without delay.
By prefetching the DNS, the browser saves time later, making the website feel faster when it loads images, scripts, or links from other domains.
Example
This example shows how to add dns-prefetch in the HTML <head> to pre-resolve the domain example.com.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>DNS Prefetch Example</title> <link rel="dns-prefetch" href="//example.com"> </head> <body> <p>Content of the page.</p> <a href="https://example.com">Visit Example.com</a> </body> </html>
When to Use
Use dns-prefetch when your webpage will load resources or links from other domains, and you want to speed up the connection to those domains.
For example, if your site loads images, fonts, or scripts from a content delivery network (CDN) or third-party services, prefetching their DNS can reduce waiting time.
It is especially helpful on slow networks or when you expect users to click links to external sites soon after loading your page.
Key Points
- dns-prefetch helps browsers resolve domain names early.
- It reduces delay when loading resources from other domains.
- It is added in the
<head>using a<link>tag. - Use it for external domains your page depends on.
- It improves user experience by making pages feel faster.
Key Takeaways
dns-prefetch to make browsers resolve domain names early and speed up loading.<link rel="dns-prefetch" href="//domain.com"> in the <head> for external domains.