Preconnect in HTML
When your page needs a file from a new server, the browser has to do three things before the first byte of that file can arrive: look up the server's address, open a connection, and agree on encryption. On a slow or distant network, that setup alone can take a noticeable fraction of a second.
<link rel="preconnect"> tells the browser to do all of that setup early, while it is busy with other work. When the page finally asks for a file from that server, the line is already open. It is one of the best hints for a page that depends on a few outside servers, and it is the one most often overused.
What You Will Learnβ
- What preconnect does, and how it goes further than
dns-prefetch - Why
crossoriginmatters, and why you may need two hints for one host - How many preconnects are sensible
- How to find the right origins for your page
- Where preconnect stops helping
- How to check that it worked
The Big Ideaβ
A preconnect names an origin (scheme and host), not a file. The browser opens a connection to it and keeps it ready.
- HTML Code
- Connection Lab
<head>
<meta charset="utf-8">
<title>The Bread Bin</title>
<!-- Images on the first screen come from this host -->
<link rel="preconnect" href="https://cdn.example.com">
<link rel="dns-prefetch" href="https://cdn.example.com">
<!-- Fonts load in CORS mode, so this one needs crossorigin -->
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="dns-prefetch" href="https://fonts.gstatic.com">
<link rel="stylesheet" href="/site.css">
</head>
<body>
<img src="https://cdn.example.com/img/hero.webp" alt="A golden loaf" width="1200" height="600">
</body>
| The page later asks for | Result |
|---|---|
| A web font (@font-face) | Needs a new connection |
| An img tag | Needs a new connection |
| An img tag with crossorigin | Needs a new connection |
| A stylesheet link | Needs a new connection |
| A classic script tag | Needs a new connection |
| A fetch() call | Needs a new connection |
You have 0 connection(s) opened early. Open only the kind you will really use.
This shows the general rule used by most browsers: requests made with credentials and requests made without them use separate connections. Details can differ between browsers, so confirm in DevTools.
In the lab, tick one hint at a time and see which kinds of request can use it. You will notice that no single hint covers everything, which is the key idea of the next sections.
What Preconnect Doesβ
For a new https host, preconnect does all of the setup steps that come before a request:
- DNS lookup: find the server's address.
- Connect: open a line to the server.
- Secure handshake: agree on encryption.
It sends no request for any file. The browser simply keeps the connection ready for when the page needs it. Compared with dns-prefetch, which only does step 1, preconnect can save much more, and costs a little more too.
An idle connection does not stay open forever. Browsers close unused connections after a short time, so a preconnect for something the page uses much later may be wasted. The exact time varies by browser.
The crossorigin Questionβ
Here is the part that surprises people. Browsers keep two separate sets of connections to the same host: one for requests made with credentials (such as cookies) and one for requests made without. They cannot share a connection.
- A plain
preconnect(nocrossorigin) prepares the credentialed connection. Images, stylesheets, and classic scripts use it. - A
preconnectwithcrossoriginprepares the anonymous connection. Fonts,fetch()calls, and anything with acrossoriginattribute use it.
If you hint the wrong one, the real request cannot use it, and the browser opens a new connection anyway. You paid for a connection nobody used.
| The page later loads | Hint it needs |
|---|---|
| An image, stylesheet, or classic script from the host | preconnect (no crossorigin) |
A font, or data with fetch() | preconnect with crossorigin |
| A mix of both | Both hints, one with and one without |
Go back to the Connection Lab and try each combination. If a host serves both kinds, you may need both hints, but remember that each one is a connection you are paying for. Browsers differ in small details, so check in DevTools which connections are really used.
How Many Is Too Many?β
Each preconnect uses time, memory, and a connection on the visitor's device and on the server. Browsers may also limit how many early connections they will open. A sensible rule of thumb is to keep preconnect for two to four origins that the page needs in its first seconds, and use dns-prefetch for the rest. Lighthouse has an audit that suggests which origins are worth preconnecting and warns about having too many, but treat that as advice and test.
Good candidates are:
- The host that serves your first-screen images (a CDN, for example)
- The host that serves your fonts
- A host your main script calls straight away
Poor candidates are anything used late, anything that needs consent first, and anything you only link to.
Pick Your Originsβ
Paste the URLs your page loads (the Network panel in DevTools can list them), and this tool extracts the unique origins, guesses which need crossorigin, and writes the hints. Then adjust each choice yourself.
Origins found (4)
<link rel="preconnect" href="https://cdn.example.com">
<link rel="dns-prefetch" href="https://cdn.example.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="dns-prefetch" href="https://fonts.gstatic.com">
<link rel="dns-prefetch" href="https://analytics.example.com">
<link rel="dns-prefetch" href="https://chat.example.com">
Preconnects chosen: 2.
This is a starting point. It guesses that origins used more often matter more, and that font files need crossorigin. You know your page better, so adjust each choice.
Preconnect vs DNS Prefetchβ
dns-prefetch | preconnect | |
|---|---|---|
| Does the DNS lookup | Yes | Yes |
| Opens the connection and handshake | No | Yes |
| Cost | Tiny | Small, but a connection stays open |
Needs crossorigin | No | Sometimes |
| Best for | Hosts you may need later | Hosts you need very soon |
Use them together for important hosts: preconnect does the work, and dns-prefetch is a fallback for browsers that do not support it. See the DNS Prefetch lesson for the reasoning.
Preconnect from a Header or a Scriptβ
Like other hints, preconnect can be sent from the server as a header:
Link: <https://cdn.example.com>; rel=preconnect
Link: <https://fonts.gstatic.com>; rel=preconnect; crossorigin
You can also add it with JavaScript when the visitor shows interest, for example on hover over a button that will load a third-party widget. That keeps the cost for people who do not need it close to zero:
const btn = document.querySelector("#open-chat");
btn.addEventListener("mouseenter", function () {
const link = document.createElement("link");
link.rel = "preconnect";
link.href = "https://chat.example.com";
document.head.appendChild(link);
}, { once: true });
Checking That It Workedβ
- Open DevTools, then Network, and reload.
- Click a request to the hinted host and open its Timing tab. The Initial connection and SSL parts should be short or missing, because they happened earlier.
- Look at the Waterfall with the connection column shown, if your browser offers it. Fewer new connections means the preconnect was reused.
- Test on a fresh cache and a slow network, because caching and fast networks can hide the difference.
- Compare a key number, such as Largest Contentful Paint (LCP), before and after.
- If the connection is not reused, check
crossoriginfirst. It is the most common cause.
Best Practicesβ
- Preconnect only to origins the page needs in its first seconds.
- Keep the list to a few.
- Use
crossoriginwhen the files load in CORS mode, such as fonts. - Hint the credentialed and anonymous connection separately if the host needs both.
- Add
dns-prefetchas a fallback. - Use origins only, with no path.
- Add it on interaction for things that load only when asked.
- Remove hints for services you no longer use, and measure after every change.
Quick Checklistβ
- Each preconnect is for an origin the page uses early
- Font and
fetch()hosts havecrossorigin - No more than a few preconnects
-
dns-prefetchadded as a fallback for the important ones - No hint for your own site
- No hint for hosts that need consent first
- DevTools shows the connection was reused
Security and Privacy Notesβ
- A preconnect sends no request, but it still reaches out. The host learns the visitor's network address and some details of the secure handshake, even if the visitor never uses the service. If you need consent before contacting certain services (analytics or advertising, for example), do not hint those hosts until consent is given. This is not legal advice, so check the rules that apply to you.
- Only preconnect to hosts you trust. A connection is a relationship. Never build hints from untrusted input, such as user-submitted links.
- Use https. Preconnecting to a plain
httphost gives you almost nothing, and sends visitors to an unencrypted service. - A broken host costs time. If a host has a certificate error or never answers, the preconnect wastes effort, and may add warnings to the console. Make sure your page works without it.
- Idle connections use server resources too, so a popular page with many preconnects can add load for the service you point at.
Global Audience Notesβ
- Distance makes connections expensive. A visitor far from the server may wait several round trips for the setup, so preconnect helps most for them. A CDN with servers near visitors reduces the gap.
- Mobile connections are slower to set up, and each extra connection costs battery. A short list is kind to them.
- Some third-party hosts are slow or blocked in some countries. A preconnect to a host that never answers is wasted time. The page must still work if the host fails.
- Test from other regions with a tool such as WebPageTest, and on a modest phone, not only your own fast machine.
Common Mistakes to Avoidβ
- Forgetting
crossoriginon font hosts. - Adding
crossoriginto image-only hosts, so the real requests cannot use the connection. - Preconnecting to a dozen hosts.
- Preconnecting to hosts used late, so the connection closes before it is used.
- Preconnecting to your own site.
- Putting a path in the URL.
- Hinting before consent for services that need it.
- Leaving hints for services you removed.
- Using it instead of fixing a late-found file that
preloador better HTML would solve. - Never checking that the connection was reused.
Practice Timeβ
- In the Connection Lab, which kinds of request can use a plain
preconnect? Which needcrossorigin? - Tick both hints. What does it cost?
- Open DevTools on a page you built, and list the third-party origins.
- Paste a few of their URLs into the origin picker, and see what it suggests.
- Change at least one suggestion, and say why.
- Add the hints, and compare the Timing tab for one request before and after.
- Add a
preconnecton hover for a widget that loads on click. - Bonus: run WebPageTest on your page, and look at which connections were opened, and when.
Quick Recapβ
Click a question to check your answer.
1. What does preconnect do?
It does the DNS lookup, opens the connection, and finishes the secure handshake for an origin early, so the page's later requests can use the ready connection. It sends no request itself.
2. How is it different from dns-prefetch?
dns-prefetch only does the lookup. preconnect does the whole setup, so it saves more, but keeps a connection open.
3. When is crossorigin needed?
When the files load in CORS mode, such as fonts and fetch() calls. A plain preconnect and a crossorigin preconnect prepare two different connections, so the hint must match the later request.
4. How many preconnects should a page have?
Only a few, for the origins needed in the first seconds. Two to four is a sensible rule of thumb. Use dns-prefetch for the rest.
5. Why can a preconnect be wasted?
Idle connections close after a short time, so a host used late may need a new connection anyway. A hint with the wrong crossorigin, or for a host the page never uses, is wasted too.
6. What privacy care does it need?
It contacts a third party before the visitor does anything, which shares their network address. Wait for consent where it is needed, and never build hints from untrusted input.
Key Takeawaysβ
- Preconnect does the connection setup early: lookup, connect, and handshake.
- It names an origin, not a file, and sends no request.
crossoriginselects which connection you prepare. Match it to the later request.- Keep the list short: a few early hosts, with
dns-prefetchfor the rest. - Pair it with
dns-prefetchas a fallback. - Add it on interaction for things loaded only when asked.
- Respect privacy: wait for consent, trust the host, and measure that the connection was reused.
Next up: Lazy Loading, where you will stop loading images and iframes the visitor has not reached yet.