Page should use the Speculation Rules API to improve loading performance
Description
The Speculation Rules API lets a page declare in advance which links a visitor is likely to follow, then have the browser quietly warm the network connection, fetch the destination document, and in some cases render it before the click happens. Page prerendering and preloading are delivered by a single <script type="speculationrules"> block declared in the document head, so the browser can start the expensive work while the visitor is still reading the current page.
Without that declaration the browser has no signal about intent, so navigation stays a cold, blocking round trip: a fresh TCP and TLS handshake, a new document request, a full layout and style pass, and a fresh script evaluation cycle on every link click. This audit checks whether the speculationrules script type is present on a page that is not already served as a prerender activation, and reports the page when the optimization opportunity is left on the table.
Common impact areas
- Returning visitors on slow connections: a prerendered next page arrives already parsed and ready to paint, which removes the blank flash and the loading spinner that otherwise follow every internal link click on a mobile or rural network.
- Core Web Vitals measurement: LCP improves because the largest element of the next page is already laid out when the user navigates, and INP improves because the main thread is not busy compiling and evaluating a document it could have compiled ahead of time.
- Conversion-critical flows: checkout, account and documentation paths lose less momentum when each step transition is instant, which directly protects revenue and form completion rates on mobile devices.
- Bandwidth and server cost: speculative fetches reuse an existing connection and follow a normal cache policy, so the work overlaps with idle time instead of adding a fresh blocking request burst on click.
- Search engine rendering budget: crawlers that follow internal links benefit from the same warm connection and cached document, reducing the wall clock time needed to walk a large site.
Why it matters
Navigation latency is the single largest contributor to perceived slowness in a multi-page site, and it is the one delay the visitor cannot anticipate. A visitor who clicks an internal link while the current page is still parsing creates a dependency chain – the browser cannot know where the click is going until the document is parsed – and every millisecond of that chain is spent staring at an empty frame.
From a metrics standpoint, speculation targets the two Core Web Vitals that dominate field data on content sites. LCP suffers on every hard navigation because the largest contentful element only starts loading after the new document commits, and interaction latency grows because the main thread must parse HTML, compile scripts and hydrate before the next click can be handled. Speculative prerendering moves that work off the critical path by starting it during idle time, which is exactly what web.dev Core Web Vitals guidance recommends for template-driven sites where most pages share a layout and data shape.
There is a second, quieter benefit. Speculation rules are declarative and inspectable, which makes the intent of a prerender auditable in the document itself rather than hidden inside a bespoke prefetch script. That matters for both debugging and governance: a team can verify at a glance which URLs are eligible, and can restate the policy in the same place where a reviewer will look for it.
Coding problems and solutions
Common coding problems
- Missing script type: the page relies on a hand-rolled prefetch loop over
<a>elements, which duplicates what the browser does natively and fires far too early, so the priority hints are ignored and the data is evicted before it is used. - Prerendering everything: the
prerenderaction is applied to an entire site including cart, checkout and account pages, so the browser spends memory and bandwidth on destinations that are either personalised or destructive to cache. - Unfiltered dynamic URLs: the
whereselector matches links containing session tokens, cart identifiers or one-time signed query strings, which pushes personalised documents into the prerender cache. - Interaction with bfcache: opting pages in for prerendering while the app also relies on
unloadhandlers, beforeunload prompts or long-lived WebSocket connections breaks the back/forward cache, producing a slower return navigation than a plain load. - Third-party script interference: analytics or tag managers that call
history.pushStatefor virtual navigation, or single page app routers that replace links with click handlers, prevent the browser from identifying a speculatable navigation at all, so the rules silently never match. - Server side rendering collision: the page is already returned as a prerendered response with an
activationStarttime from the server, and the same ruleset also runs in the document, so the browser attempts a second prerender and reports a console error.
How to fix it
Add a baseline speculation rules script
Place the script in the document head as static markup so the browser can parse the intent before it discovers any link. Start with prefetch, which is the conservative option: the response is fetched and stored in the HTTP cache but no scripting or rendering happens, so there is no risk of running speculative code.
<head>
<script type="speculationrules">
{
"prerender": [
{
"source": "list",
"urls": ["/products/*", "/docs/*"],
"eagerness": "moderate"
}
],
"prefetch": [
{
"source": "document",
"where": {
"href_matches": "/*",
"selector_matches": ".site-nav a",
"not": {
"href_matches": ["/cart*", "/checkout*", "/account*", "/logout*"]
}
},
"eagerness": "moderate"
}
]
}
</script>
</head><head>
<script type="speculationrules">
{
"prerender": [
{
"source": "list",
"urls": ["*"]
}
]
}
</script>
</head>Gate the feature on browser support
Unsupported browsers ignore the script entirely, which is safe, but your own logic should still feature-detect before relying on the behaviour. The same HTMLScriptElement.supports check used by this audit tells you whether the script type is understood on the current engine.
const SPECULATION_RULES_TYPE = 'speculationrules';
const isSupported = (): boolean => {
if (typeof HTMLScriptElement.supports !== 'function') {
return false;
}
return HTMLScriptElement.supports(SPECULATION_RULES_TYPE) === true;
};
if (isSupported()) {
document.head.insertAdjacentHTML('beforeend', speculationRulesMarkup);
}// Guessing support, and injecting speculative work into every browser.
if (navigator.userAgent.indexOf('Chrome') > -1) {
const script = document.createElement('script');
script.setAttribute('type', 'speculationrules');
script.innerHTML = JSON.stringify({ prerender: [{ source: 'list', urls: ['*'] }] });
document.head.appendChild(script);
}Tune eagerness to measured risk
Eagerness is the most important tuning decision. moderate triggers on pointer or focus interaction, conservative waits for the pointer to dwell, and eager speculates immediately on page load. Default to moderate and raise eagerness only for the small set of URLs that dominate real traffic.
<script type="speculationrules">
{
"prefetch": [
{
"source": "document",
"where": { "href_matches": "/pricing*" },
"eagerness": "eager"
},
{
"source": "document",
"where": { "href_matches": "/blog*" },
"eagerness": "conservative"
}
]
}
</script><script type="speculationrules">
{
"prefetch": [
{
"source": "document",
"where": { "href_matches": "/*" },
"eagerness": "eager"
}
]
}
</script>Keep back/forward cache alive
Speculation is a net loss if it disables the back/forward cache, because a restored page is faster than any speculative reload. Remove unload listeners, keep beforeunload usage to a genuine unsaved-changes case, and use pagehide for teardown instead of unload.
const persistConnections = (): void => {
globalThis.addEventListener('pagehide', (event) => {
if (event.persisted === false) {
return;
}
closeTelemetrySocket();
});
};globalThis.addEventListener('unload', () => {
closeTelemetrySocket();
persistDraftLocally();
});Verify the effect in DevTools before shipping
Confirm the feature is actually firing rather than trusting the markup. The Application panel lists active speculation rules, and the console reports rule parse errors, unsupported selectors and activation failures. Pair the check with a network trace to see prerender requests and with a performance trace to compare LCP before and after.
const measureSpeculation = async (): Promise<void> => {
try {
const entries = globalThis.performance.getEntriesByType('navigation');
const navigationEntry = entries.at(0);
if (navigationEntry === undefined) {
return;
}
console.info('activationStart', navigationEntry.activationStart);
console.info('LCP', navigationEntry.domContentLoadedEventEnd);
} catch (err) {
console.warn('Speculation metrics unavailable', err);
}
};// Shipping the ruleset and assuming they are honoured.
console.info('speculation rules added');Known Limitations
- Browser support: the API is not universally available. Engines that do not implement it ignore the
speculationrulesscript, so the rule reports the absence of the tag but the corresponding performance gain simply does not materialise on those clients. - Already prerendered pages: when the server delivers a prerendered response, the navigation entry exposes a positive
activationStartand the page is already optimal. This rule deliberately skips such pages, so a page can be reported as compliant through two entirely different mechanisms. - Single page applications: client-side routers that intercept clicks and call
pushStatedo not produce a navigable document for the browser to speculate, so the ruleset may be present and correct on the page while never triggering. - Shadow DOM and iframes: a
whereclause that traverses shadow roots or crosses an iframe boundary does not see the links inside it, so navigation targets declared in a component’s shadow tree are silently excluded. - Non-idempotent destinations: speculative activation can fire a document request for a URL that later cancels. Routes that mutate state on a GET request, or that are not safe to warm, must be excluded explicitly, and mistakes here are difficult to detect from logs alone.
- Authenticity and cache separation: speculation rules are subject to the same cache partitioning as ordinary navigation, so a speculative fetch cannot populate the cache for a different user, which limits the benefit on sites where every visitor is served a personalised document.
Resources
- MDN: the full API reference, supported selector syntax and browser compatibility table are documented at Speculation Rules API.
- W3C: the underlying pre-rendering and cross-document communication work is specified in the Speculation Rules specification, including the normative
eagernessvalues and matching conditions. - web.dev: the practical rationale and the LCP and INP improvement argument is covered in prerendering for fast navigation.
- Chrome Developers: implementation guidance, safe pattern design and rollout advice sit in the prerendering documentation, and the DevTools workflow in the Application panel reference.
- WHATWG HTML: the script element type registry entry that makes the tag valid, and the normative conditions under which it is honoured, are in the HTML specification.
Rule
- Audit: performance
- Standard: SiteLint
- Level: Best practices
- Success Criteria: N/A
- Rule ID:
speculation-rules