What is the difference between prefetch vs preconnect? Before we can answer that question we should explain first what each of the actually is, what it does and when should we use it.
<link rel="dns-prefetch" href="//www.domain.com">
The dns-prefetch attribute tells the browser that the resource will be needed in the future and instructs it to resolve the DNS as quickly as possible.
So if we know we will most likely need a resource like an image, audio file or something else we can add this instruction, so that when the browser actually needs to resolve the request it will no longer have to wait for the DNS to resolve.
This might seem like a small improvement but for high performance websites any optimisation helps.
Now we also need to explain that not all browsers yet support this functionality (most modern browsers fo) so please have a look if you need to support a specific browser with this feature.
So to simplify this, DNS prefetch just resolves the DNS lookup of an asset before we actually request it to save us some time.
<link rel="preconnect" href="https://www.domain.com">
The preconnect attribute, does everything that dns-prefetch does, but it also goes one step further and it will also make the TCP handshake, and optional TLS negotiation.
Now this are all relatively expensive roundtrips which we can do in advance to resolve the anticipated request faster.
DNS prefetch vs preconnect
As you can see the preconnect directive follows the same logic as dns-prefetch, it just does more work beforehand to save even more time. We must also be aware that both of them are useful only for third party domains, such as CDNs or social media images, if we are loading assets from the same domain the browser doesn’t need to do a DNS lookup as it already did it to resolve the initial request.
When to use each?
Now how would you decide which one to use? In my opinion, I would increase the amount of steps you do before a request in line with certainty that you will actually need to resolve that request.