preconnect allows the browser to set up early connections before an HTTP request is actually sent to the server. Connections such as DNS Lookup, TCP Handshake, and TLS negotiation can be initiated beforehand, eliminating roundtrip latency for those connections and saving time for users.
With the use of the new
preconnect hint, we are able to give modern browsers a better idea of what connections should be initiated before actual requests for information are requested. This method is favourable over the previous method where browsers try to predict which websites they should use
preconnect with on their own.
preconnect can be added directly to a link tag as an attribute in the HTML. It can also be delivered through the
<link href='https://cdn.keycdn.com' rel='preconnect' crossorigin>
According to W3C Resource Hints, to initiate a
preconnect, the user agent must carry out the following 6 steps:
- Resolve the URL defined by the
- Let origin be preconnect URL's origin.
- Let corsAttributeState be the current state of the element's
- Let credentials be a boolean value set to
- If corsAttributeState is
Anonymousand origin is not equal to current Document's origin, set credentials to
- Attempt to obtain connection with origin and credentials.
The following example, from Ilya Grigorik's blog, shows the comparison of latency times between loading resources with
preconnect vs without
preconnect. The first image displays a timeline of assets without the use of
preconnect. As can be seen, the initial DNS, TCP, and TLS connections must be set for the initial HTML document.
Once this is complete, the same connections must take place for the css file which reveals that the page needs two fonts. Finally, connections are established for the DNS, TCP, and TLS of the font origin, from which both fonts can be downloaded in parallel. In total, the files take just over 2.6 seconds to load.
preconnect is used, the same initial DNS, TCP and TLS connections are established for the HTML document. However, the initial connections for the fonts can be established at the same time as the css file. This means once the css file is done downloading, the font files do not have to wait for the initial connections to be established but rather can just begin downloading - resulting in a time savings of ~0.6 seconds.
preconnect successfully allows you to reduce the amount of round trips needed, efficiently initiate connections and decrease page load time.
preconnect with modern browsers can certainly help improve website performance as seen by the example in this article. Reducing the amount of round trips always plays a large part in optimizing page load times. However, as
preconnect anticipates the use of connections, it opens sockets that may go unused which is suboptimal for both the client and server. Using
preconnect in an efficient and thought out manner will not only help optimize your website but will also keep you from underutilizing resources.