Prefetch, preload and preconnect

In many cases when we load our website we know that we will be making calls to external elements, to other hostnames, both ours and to third parties.

These calls to other hostnames will require requests to be made to the DNS at the time the item is found. To do this, we will use the preconnect system, which will basically make a call to precalculate the DNS before the actual request is made.

Preconnect

Preconnect is a measure similar to DNS prefetching, which can be used in parallel without loss of performance, since the functions “complement” each other, i.e. if the DNS prefetch was executed first, its results are then used in the preconnect.
The preconnect directive allows the browser to establish connections before an HTTP request is actually sent to the server. This includes DNS lookups, TLS negotiations, TCP handshakes and in turn, it eliminates roundtrip latency and saves time for users.

This call, when made previously and in parallel with other elements, will reduce the time to load the other element.

Any hostname other than the domain name should be in this preconnect system.

An example of a call might be similar to this one:

<link rel="preconnect" href="https://www.example.com/">

Prefetch

On the other hand, we can assume that when a user enters a page that is not the main page of the site, he or she can enter it. Or, for example, that an item that is paged after page 1 will load page 2, or that a user who is in a store will end up in a shopping cart.

In these cases, we can consider loading another page or content in the browser cache so that, if this happens, it will be much faster.

An example could be similar to this:

<link rel="prefetch" href="/index.html" as="document">

Preload

Finally, we can also preload elements to be used later in the page. In this case, it can be applied with certain frequency to elements that we know can block the loading of the page, such as certain scripts.

<link rel="preload" href="/critical.js" as="script">

The valid values of the “as” parameter are

audio: <audio>
document: <iframe> and <frame>
embed: <embed>
font: CSS @font-face
image: <img> and <picture>
object: <object>
script: <script>
style: <link rel=stylesheet> and CSS @import
track: <track>
video: <video>
worker: Workers