All the answers so far seem either simplified, incomplete or partially wrong (topic is complex, things are confusingly named and not well documented!), so here's my understanding:
To be able to reuse the connection created by <link rel=preconnect>
, things depend on what kind of content you want to fetch, from where, whether the request will send browser credentials (which can be established by the browser explicitly or implicitly):
The request is same-origin (example.com
requests subresource from example.com
)
There's no need for preconnect
at all in the first place; the browser keeps the connection open after loading the page for quite a while.
If there are multiple connections to be opened, the browser decides by itself if and how many to open (depending if server announces HTTP/2 support in TLS handshake, browser settings etc.)
to be checked: what if same-origin request has crossorigin
attribute: is it used or ignored?
The request is cross-origin (example.com
requests subresource from another.com
)
- if the actual request has
crossorigin
attribute explicitly set in HTML (crossOrigin
in JS - case is important), the preconnect must also have it, with same value (perhaps except in cases where it doesn't make sense and crossorigin
is ignored -- not fully clear for me yet)
- else, if request if for
<script type=module>
: to be checked
- else, if request is and "old school" request for
<img>
, <style type=stylesheet>
, <iframe>
, classic <script>
etc. (initiated via HTML or JS) without crossorigin
explicitly specified, then the preconnect MUST NOT have crossorigin
attribute set.
- else, if request is a cross-origin font request, preconnect must have
crossorigin=anonymous
- else, if request is a cross-origin
fetch
or XHR
:
- if it is done in credentialed mode (i.e. cookies are attached or HTTP basic auth is used; in case of fetch, this means
credentials !== omit
; in case of XHR: withCredentials === true
): preconnect must have crossorigin=use-credentials
- if it is not in credentialed mode: preconnect must have
crossorigin=anonymous
For the last case (fetch/XHR), go to network panel in Chrome/Firefox devtools, right click a request, and choose copy as fetch
from a dropdown. This will create a snippet of JS, which will tell you if that request is CORS-enabled ("mode"=="cors"
) and credentialed ("credentials"=="include"|"same-origin"
).
Note however the trick above doesn't work correctly for non-XHR/fetch requests, because for example fetch
and <img>
use different algorithms to establish connection, as explained before.
Finally, in HTML, <link ...crossorigin>
=== <link ...crossorigin=anonymous>
.
Additional notes and links: