Crossorigin Attribute in Hints
You'll learn how to properly handle credentials when using resource hints with CORS resources.
Why Crossorigin Matters in Resource Hints
When you use resource hints like preconnect, prefetch, or preload to optimize loading of resources from other domains (fonts, scripts, stylesheets), the browser needs to know whether those resources require credentials (like cookies or authentication headers).
Without the crossorigin attribute, the browser makes two separate connections: one for the hint and another for the actual resource request. This defeats the entire purpose of your optimization!
The Problem: Duplicate Connections
Imagine you hint the browser to preconnect to a font server, but when your CSS actually requests that font, it needs CORS. The browser treats these as different requests and opens a second connection, wasting time and bandwidth.
The Solution: Match Credentials Mode
Add the crossorigin attribute to your resource hints to match how the resource will actually be fetched:
<!-- Without credentials (anonymous mode) -->
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="preload" href="https://cdn.example.com/font.woff2"
as="font"
type="font/woff2"
crossorigin>
<!-- With credentials (use-credentials mode) -->
<link rel="prefetch" href="https://api.example.com/data.json"
crossorigin="use-credentials">
The crossorigin attribute (or crossorigin="anonymous") tells the browser: "This resource uses CORS without credentials." Use crossorigin="use-credentials" when cookies or auth headers are needed.
Key Takeaway: Always add the crossorigin attribute to resource hints when loading CORS resources to ensure the hint and actual request share the same connection, maximizing performance gains.