preconnect vs dns-prefetch resource hints

Robin Drexler picture Robin Drexler · Nov 13, 2017 · Viewed 13k times · Source

https://www.w3.org/TR/resource-hints/

If I understand correctly, both are used to initiate an early connection to load resources faster at a later time.

preconnect is just doing "more".

Apart from a better browser support, is there any reason to use dns-prefetch over preconnect? I've also seen websites using both rel at the same link tag in order to use preconnect if possible and fall back to dns-prefetch if not.

<head>
  <link
    rel="dns-prefetch preconnect"
    href="https://fonts.gstatic.com"
    crossorigin
  >
</head>

Answer

jakub.g picture jakub.g · Jun 27, 2018

I've been researching the topic a bit lately and so far my (theoretical) conclusions are as follows:

Browser support difference is negligible as of mid-2018, when counting the real global usage of browsers (~73% vs ~74%)

dns-prefetch = DNS and preconnect = DNS + TCP + TLS. Note that DNS lookup is quite cheap to perform (a simple query-response to the DNS server, that is cached in the browser for a short amount of time), whereas TCP and TLS involves some server resources.

The practical difference is hence, if you know that a server fetch will happen for sure, preconnect is good. If it will happen only sometimes, and you expect huge traffic, preconnect might trigger a lot of useless TCP and TLS work, and dns-prefetch might be a better fit.

For example:

  • if the page requests https://backend.example.com/giveMeFreshData on each load, and the response is not cacheable, preconnect is a good fit
  • if the page only requests a static resource like https://statics-server.example.com/some-image.jpg or https://statics-server.example.com/some-css.css, and the resource is very likely to come from the user's browser cache (the very same resource(s) is used on many pages, and your user will trigger a lot of page loads like this with the warm cache -- and no other resources are fetched from that origin), then preconnect might be creating a lot of unnecessary TCP connections on your server (that will abandoned after a few seconds, but still, they were not necessary in the first place) and TLS handshakes (however in such case, preload might be an option if you know the exact URL and the resource is very important).
  • If the traffic on your website is small though, it should not be impacted too much by this difference, so preconnect is probably a good fit for low-traffic websites, regardless of the things mentioned before.

As always, it's best to think about the use cases, deploy, measure, and fine tune.