Concept in Performance
Resource hints (preload and preconnect)
Published Updated
Resource hints are <link> relations that let a browser fetch a resource or prepare a
connection before the resource is otherwise requested. preload and modulepreload serve the
current navigation. preconnect and dns-prefetch prepare connection work that a later request
may use; prefetch prepares the resource itself.
How it works
Section titled “How it works”The HTML Standard defines preload as a request to fetch and cache a resource for the current
navigation. The as attribute supplies its destination, and fetchpriority supplies its priority.
The later request can reuse that response when its URL and request settings match the hint. MDN
states that supplying as lets the browser store the resource in the cache for future requests,
apply the correct Content Security Policy, and set the correct Accept request headers.
modulepreload uses the module-script fetch rules and stores the result in the document’s module
map. The HTML Standard allows an implementation to fetch the module’s dependencies too. A plain
preload with as="script" uses the preload cache instead and does not populate that module map.
preconnect names an origin instead of a file. The Resource Hints specification says a user agent
should attempt the connection handshake early. For HTTP this includes both DNS and TCP; HTTPS can also
include TLS. The same specification permits a partial handshake or no handshake when resources or
other conditions prevent the full operation. dns-prefetch asks only for early name resolution.
web.dev describes prefetch as a low-priority request for a resource likely to be used for future
navigations.
Match the hint to the real request
Section titled “Match the hint to the real request”The attributes on a preload describe the request that will consume its response. Keep them aligned
with the request that follows. That request can come from a stylesheet or <script crossorigin>,
for example. The same rule applies to a font face and an image. It also applies to fetch().
Resource hints can be declared in <head>. JavaScript exposes the reflected CORS setting as
crossOrigin.
| Attribute | Effect on the request |
|---|---|
href |
Identifies the resource. The consuming request needs the same URL to reuse the response. |
as |
Sets the fetch destination. MDN lists font and image among its values. It also lists script and style, as well as fetch. |
crossorigin |
Selects the CORS and credentials mode. Font fetches use anonymous CORS mode, including same-origin font fetches, so their hints need crossorigin. |
type |
Gives the resource MIME type. A browser can skip a format it does not support. |
fetchpriority |
Supplies the priority used by the preload processing model. |
Common destinations appear in markup as as="font", as="image", as="script", and
as="style". web.dev describes an omitted or invalid as value as equivalent to an
XMLHttpRequest for prioritization, and says it can cause some resources, such as scripts, to be
fetched twice.
Chromium maps resource types to initial priorities in TypeToPriority. Its
ComputeLoadPriority logic lowers a link-preloaded font so it does not take precedence over
critical CSS or parser-blocking scripts. These function names describe Chromium’s implementation;
the portable authoring inputs remain as and fetchpriority from the HTML processing model.
The Google performance guidance documents two concrete mismatch results. A font preload without
the required crossorigin is fetched again for the font request. Omitting as can also cause some
resources, such as scripts, to be fetched twice. For responsive images, its resource-hints guidance
uses imagesrcset so the hint selects the same image candidate as the later image request.
Choose the relation by timing and target
Section titled “Choose the relation by timing and target”preload fetches a named resource for the current navigation. preconnect starts connection setup
to an origin without naming the file a later request will use. Choose preload when the resource
URL and request settings are known; choose preconnect when the origin is likely to be used but the
later resource is not yet named.
Use preload for a resource needed by this document when normal discovery happens later, such as a
font referenced from a stylesheet. Use modulepreload when the target is a JavaScript module that
the document will evaluate. Use preconnect for an origin that the document is likely to contact;
the HTML Standard describes it as useful when resources from that origin are highly likely to be
required. The web.dev resource-hints guidance recommends reserving it for the most critical
cross-origin connections when a page uses many origins.
Use dns-prefetch when early DNS resolution is useful without requesting a connection handshake.
Use prefetch for a resource associated with a future navigation. web.dev describes it as a
low-priority request for a resource likely to be used for future navigations.
Check support without making a request
Section titled “Check support without making a request”HTMLLinkElement.relList exposes the element’s rel tokens as a live DOMTokenList.
DOMTokenList.supports() reports whether the list supports a supplied token. Calling
link.relList.supports() is therefore a relation check; test that supports()
exists before calling it, then keep the ordinary resource request in the page so the hint remains an
optimization rather than the only route to the resource.
BCD html.elements.link.rel.preload records preload from Chrome 50 and Safari 11.1. Firefox
enabled it in 56, disabled it in 57 because of web compatibility problems, and enabled it again in
85. BCD records preconnect from Chrome 46 and Firefox 39; Safari support starts at 11.1. For
modulepreload, BCD records Chrome 66 and Firefox 115; Safari support starts at 17. The linked browser compatibility
tables provide the site’s broader browser data; the relation-specific
versions here come from the cited BCD path.
Examples
Section titled “Examples”The font pattern assumes that the named font and stylesheet already exist in your application. The module example supplies every file and command needed for a local run. Both keep the consuming request present. A hint does not apply a stylesheet or display an image, and it does not execute a module by itself.
Preloading a font with matching request modes
Section titled “Preloading a font with matching request modes”This integration pattern preloads the same font URL used by @font-face. It is not a standalone
demo: provide /fonts/brand.woff2 and /styles/app.css in your application before using it. The
as and type attributes describe the font request. crossorigin supplies its CORS setting,
while the stylesheet remains responsible for using the font.
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <link rel="preload" href="/fonts/brand.woff2" as="font" type="font/woff2" crossorigin> <link rel="preconnect" href="https://api.example.com" crossorigin> <link rel="stylesheet" href="/styles/app.css"> <title>Matching a font preload</title> </head> <body> <h1 class="brand">Resource hints</h1> </body></html>Define /fonts/brand.woff2 under @font-face in /styles/app.css with the same URL. If the font
server requires another URL or credentials mode, change both the hint and the consuming request so
their request settings continue to match.
The same request can be inserted with JavaScript. Set the request-shaping properties before href,
then append the link.
function preloadFont(href) { const link = document.createElement('link'); link.rel = 'preload'; link.as = 'font'; link.type = 'font/woff2'; link.crossOrigin = 'anonymous'; link.href = href; document.head.append(link);}Separate hints can prepare a font and an API origin. Another hint can prepare a module, which still
needs a later module script or import() call to execute.
<link rel="preload" href="/fonts/brand-sans.woff2" as="font" type="font/woff2" crossorigin><link rel="preconnect" href="https://api.example.com"><link rel="modulepreload" href="/scripts/app.3f2a1c.js">Keep the matching @font-face and API request in the page. Keep the module import too. These hints
start work early but do not replace the requests that consume their results.
Falling back when modulepreload is unavailable
Section titled “Falling back when modulepreload is unavailable”Create an empty directory and save the next block as index.html. It checks modulepreload, adds
the hint when supported, and calls import() whether or not the hint was added. The fallback loses
the early module fetch, but it keeps the route that loads and executes the module.
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <title>modulepreload fallback</title> <script type="module"> const moduleURL = new URL('./editor.js', document.baseURI).href; const probe = document.createElement('link'); const supportsModulePreload = 'relList' in probe && typeof probe.relList.supports === 'function' && probe.relList.supports('modulepreload');
console.log(`modulepreload supported: ${supportsModulePreload}`);
if (supportsModulePreload) { const hint = document.createElement('link'); hint.rel = 'modulepreload'; hint.href = moduleURL; document.head.append(hint); }
window.addEventListener('DOMContentLoaded', async () => { const status = document.querySelector('#status'); try { const { startEditor } = await import(moduleURL); startEditor(status); } catch (error) { status.textContent = 'Editor import failed'; console.error('Editor import failed', error); } }); </script> </head> <body> <p id="status">Loading editor...</p> </body></html>Save this second file beside it as editor.js. It supplies the export consumed by the dynamic
import, so the example has no application-specific dependency.
export function startEditor(target) { target.textContent = 'Editor started'; console.log('Editor started');}Start an HTTP server from that directory, then open http://localhost:8000/. Do not open the HTML
through a file: URL, because this run uses an HTTP module request.
python3 -m http.server 8000index.html resolves both the hint and the import to
http://localhost:8000/editor.js. They are same-origin, so this setup needs no CORS response
headers. The expected observation (not a measurement from this article) is a successful 200
entry for editor.js in Network. Console shows a modulepreload supported: true or false line;
Editor started appears in both the page and Console. When support is reported as true, the hint fetches
the module before import() consumes the same module URL; when it is false, import() remains the
working request.
If the page says Editor import failed, inspect the editor.js row in Network. For a 404, confirm
that the server was started in the directory containing both files and that the filename has the
same letter case. If you move editor.js to another origin, either restore the same-origin URL or
configure that server to allow the page origin with Access-Control-Allow-Origin, then use the same
absolute module URL for the hint and import().
See also
Section titled “See also”- HTML Standard: link type
preload(whatwg.org) - Resource Hints (w3.org)
- Assist the browser with resource hints (web.dev)
- Font and image optimization
- Code splitting with dynamic import()
- Speculation Rules API
- Browser compatibility by browser
Specifications
| Specification | Status |
|---|---|
| None. | |