Speed up websites using DNS prefetching
We recently added a couple of lines of HTML to our mobile website that potentially speeds it up for users with recent browsers (Chrome and Firefox, at the time of writing). The technique might not work for all sites, but it applied very well to ours. I’ll explain how and why:
- You add a
<link rel="dns-prefetch" href="//1.vgc.no" />tag to the <head> of your site.
- The hostname you specify will be resolved by the browser in an asynchronous fashion
- When resources located at this hostname is to be loaded, the hostname is already mapped to an IP-address and thus the request takes less time
The solution works well on our site for the following reasons:
- We load resources from many different hostnames – mostly to get around a bug in Safari for iOS that we’ve written about earlier
- We lazy-load images on our site to reduce the bandwidth. For each image located on a hostname the browser has not resolved, there is first a DNS lookup and then the actual request to load the image. On mobile devices with high-latency connections, doing the DNS lookup as early as possible is a big win in terms of performance
- Unfortunately, some of the ad-systems we use load in a synchronous way, blocking the rest of the page from loading. While this is happening, we can still resolve the hostnames so they are ready to use.
As you can see from the screenshots above, we gained quite a bit of performance from this little trick. There are a number of reasons why this might not work as well for your site, however:
- If your markup is loaded and parsed quickly enough, the DNS resolving won’t be finished before it starts loading resources from the domains you’ve specified
- You might be loading few resources, or the resources you load are located on the same hostname
If you think this technique might help your site, give it a try! It’s just a line or two of HTML, and it’s pretty easy to see how it affects your website using for example WebPageTest.org. Make sure you pick a browser that supports DNS-prefetching (Chrome, for example).