Imagine your website's pages popping up almost instantly—like landing on a teleportation pad instead of a slow-loading dock. That's the vibe the Speculation Rules API brings. The Speculation Rules API is an experimental yet powerful tool designed to prefetch or prerender likely navigations, boosting perceived performance. It's a modern replacement for outdated <link rel="prerender">
and enhances older prefetch methods with richer control and safety.
Let's set sail and explore how this powerful tool delivers smoother browsing with minimal effort.
What is the Speculation Rules API?
At its core, this API lets developers hint to the browser:
"Here are pages the user might visit next—go ahead and fetch them now."
- Prefetching fetches just the response body of a future page (no subresources). It saves bandwidth and speeds up navigation—but offers a lighter performance boost.
- Prerendering renders and loads everything—subresources, scripts, data—into an invisible cache. When the user navigates, activation is near-instant. But it consumes more memory, CPU, and bandwidth.
The API lets you define these behaviors using JSON rules, either embedded as:
-
<script type="speculationrules">
tags in HTML, or - External JSON files linked via the
Speculation-Rules
HTTP header.
👉 MDN emphasizes that these rules supersede older mechanisms and should be preferred where supported.
Key Benefits Over Older Techniques
Feature | Speculation Rules API |
<link rel="prefetch"> / Deprecated <link rel="prerender">
|
---|---|---|
Control over resources fetched | ✅ Yes (prefetch vs prerender, eagerness) | ❌ No differentiated handling |
Respects user power-saving modes | ✅ Yes | ❌ No |
Cache isolation per page | ✅ Yes (in-memory cache) | ❌ No |
Cross-site navigation support | ✅ Prefetch-only when cookie-less or opt-in | ❌ No |
Not blocked by Cache-Control | ✅ Speculation allowed even if HTTP cache is blocked | ❌ Often blocked |
Implementation Patterns
1. Embedding Rules in HTML
<script type="speculationrules">
{
"prerender": [{
"where": { "selector_matches": ".prerender" },
"eagerness": "eager"
}],
"prefetch": [{
"where": { "selector_matches": ".prefetch" },
"eagerness": "moderate"
}]
}
</script>
This enables dynamic behavior: apply .prefetch
or .prerender
CSS classes on links to control speculation.
2. Inject via JavaScript
You can conditionally inject rules based on user interactions (e.g., after adding to cart). Great for tag managers or A/B testing.
3. Via HTTP Header
Speculation-Rules: "/speculationrules.json"
Serve a JSON file with application/speculationrules+json
type—handy for CDN deployment and easier rollout without modifying HTML.
Rolling It Out: A Guided Strategy
Start with Prefetch
A low-risk, broad-sweep way to gain speed. Great for typical navigations like homepage → article.Move to Low‑Risk Pre‑render
Use moderate eagerness when the next destination is predictable. Minimize overhead but still improve performance.Finally, Implement Eager Pre‑renders
With strong data (e.g., top funnels), use eager prerender for 1–2 highly likely navigations. Beware: Chrome caps at ~2–10 concurrent prerenders.
🌱 1. Start with Prefetch (Low-Risk, Low-Cost)
Use prefetching to speed up likely next-page loads, without executing scripts or rendering the DOM.
<!-- Add the "prefetch-next" class to links likely to be clicked soon -->
<a href="/about" class="prefetch-next">About Us</a>
<script type="speculationrules">
{
"prefetch": [
{
"where": {
"selector_matches": ".prefetch-next"
},
"eagerness": "moderate"
}
]
}
</script>
What's happening:
- This rule tells the browser: If you see any
.prefetch-next
link, prefetch the destination page. -
eagerness: "moderate"
avoids excessive resource use (vs.eager
, which starts immediately).
🌿 2. Move to Low-Risk Prerender (Faster, Still Safe)
<!-- Add a "prerender-safe" class to pages that are highly likely and side-effect-free -->
<a href="/product/123" class="prerender-safe">View Product</a>
<script type="speculationrules">
{
"prerender": [
{
"where": {
"selector_matches": ".prerender-safe"
},
"eagerness": "moderate"
}
]
}
</script>
Bonus: Add runtime behavior if prerendered
if (document.prerendering) {
// Pause analytics or expensive tasks
document.addEventListener("prerenderingchange", () => {
startAnalytics(); // Run only after activation
});
} else {
startAnalytics(); // Normal page load
}
🌳 3. Implement Eager Prerenders (Predictive & Fastest)
<a href="/signup" class="eager-prerender">Start Free Trial</a>
<script type="speculationrules">
{
"prerender": [
{
"where": {
"selector_matches": ".eager-prerender"
},
"eagerness": "eager"
}
]
}
</script>
Optional: Clear prerender cache on logout or major state change
Clear-Site-Data: "prefetchCache"
Summary Table
Phase | Code Pattern | Risk Level | Performance Boost |
---|---|---|---|
Prefetch only |
.prefetch-next with prefetch
|
✅ Very Low | ⚡ Small |
Moderate prerender |
.prerender-safe with prerender
|
⚠️ Medium | ⚡⚡ Faster |
Eager prerender |
.eager-prerender with eager prerender |
❗ Higher | ⚡⚡⚡ Fastest |
Safety First: Pitfalls to Avoid
Unintended Side‑effects
Avoid speculative fetching on actions like add-to-cart, logouts, OTP triggers. Use theSec-Purpose
header to detect and suppress side effects.-
Stale or User‑specific State
Example: prerendered page shows "logged out" view after login. Fix by refreshing state post-activation via:- Broadcast Channel API to sync across pages.
- WebSocket or fetch() to revalidate data.
Analytics & Ads
Guard analytics/event scripts usingdocument.prerendering
. Useprerenderingchange
to trigger them only once visible.Clear Speculative Cache on State Changes
After logout, avoid stale prefetched pages:
Clear-Site-Data: "prefetchCache"
- API Restrictions in Prerender Certain APIs are deferred or no-opped until activation (e.g., notifications, geolocation, full-screen, WebRTC).
Measurement: Did It Work?
Track improvements in LCP, CLS, and INP—but focus on specific paths, not site-wide metrics.
Detect speculation behavior:
console.log(document.prerendering);
console.log(performance.getEntriesByType("navigation")[0]?.activationStart > 0);
Log this to measure speculation efficiency with Real User Monitoring (RUM).
Summary and Final Tips
The Speculation Rules API is a powerful, modern approach to make page transitions nearly instant.
- Roll out gradually: prefetch → moderate prerender → eager prerender.
-
Watch out for:
- Unwanted effects (side-effects on load).
- Stale or conflicting application state.
- Analytics and ad misfires.
- API constraints during prerender.
âś… Always measure, iterate, and adjust based on real user data.
Sample Implementation Snippet
<script type="speculationrules">
{
"prefetch": [{
"where": { "selector_matches": ".likely-next" },
"eagerness": "moderate"
}],
"prerender": [{
"where": { "urls": ["/checkout", "/product-detail"] },
"eagerness": "eager"
}]
}
</script>
if (document.prerendering) {
console.log("Prerendering in background; deferring analytics.");
} else {
runAnalytics();
}
The Speculation Rules API is one of the most promising ways to enhance perceived performance—and it's already supported in Chromium-based browsers. Now's the time to test, experiment, and share what works. 🚀
Top comments (0)