CoreGamix — Full-Stack Engineering & Developer ToolsCoreGamix — Full-Stack Engineering & Developer Tools
  • Angular
  • Web Development
    • React & TypeScript
    • Node.js
    • PHP & MySQL
  • Tech & AI News
  • Tools & Plugins
  • About
  • Contact Us
HomeWeb Development SEO & Performance Speculation Rules API Guide: Cut Route LCP to 38ms Without Phantom Analytics

Speculation Rules API Guide: Cut Route LCP to 38ms Without Phantom Analytics

Anil Mehra on November 30, 2026
SEO & Performance Web Development
speculation rules api instant prerender LCP guide banner
7 Min Read

In my multi-tenant billing and docs portal, cold server-rendered route clicks stalled at 680ms P75 Largest Contentful Paint even after edge caching, while my first naive rollout of the Speculation Rules API inflated pageview counts by 38% and accidentally triggered logout endpoints on pointer hover. Adding CSS selector exclusions and a twenty-line TypeScript activation guard cut navigation LCP down to 38ms without firing a single phantom analytics event.

Most performance posts paste a five-line wildcard snippet and stop there. However, real SaaS apps mix public pricing pages with authenticated invoice views, rate-limited endpoints, and strict telemetry pipelines. Below, I’ll walk through the exact document rules, TypeScript guards, and backend header checks I ship in production alongside Angular incremental hydration SSR and multi-page architectures.

Why Wildcard Prerendering Backfires With the Speculation Rules API

Legacy <link rel="prerender"> hints were deprecated years ago because browsers couldn’t predict resource budgets safely. Instead, modern Chromium browsers parse JSON rule sets inside <script type="speculationrules"> blocks or Speculation-Rules HTTP response headers to prefetch or fully render target URLs inside a hidden background renderer process.

That default burns server CPU if left unchecked. Specifically, when you set "href_matches": "/*" with immediate or eager eagerness, Chrome spins up background renderers before the user even moves their mouse. As a result, JavaScript bundles execute early, session cookies refresh out of order, and unclicked hovers hit your database.

Speculative Loads and Route LCP Diagnostic comparing 680ms cold navigation with 38ms prerendered activationStart
Comparing cold MPA navigation (680ms) against Speculation Rules prerendering (38ms activationStart LCP) while excluding stateful /auth/logout routes.

Start with moderate eagerness first. Under the MDN Speculation Rules specification, moderate waits until a user hovers a link for roughly 200ms or presses pointerdown on mobile. Therefore, you capture genuine navigation intent while cutting wasted background renders by more than 75% in my production logs.

Scoping Document Rules With Moderate Eagerness and Exclusions

Never prerender URLs that mutate server state on GET requests. For example, links like /auth/logout, /invoices/download-pdf, or one-click cart actions will execute inside the hidden tab the instant a user pauses their cursor nearby. Rather than maintaining brittle URL arrays by hand, I combine path allowlists with CSS selector exclusions.

<script type="speculationrules">
{
  "prerender": [
    {
      "where": {
        "and": [
          { "href_matches": ["/pricing/*", "/docs/*", "/invoices/*"] },
          { "not": { "selector_matches": ".no-prerender, [data-stateful], [href^='/auth/']" } },
          { "not": { "href_matches": "*\\?*action=*" } }
        ]
      },
      "eagerness": "moderate"
    }
  ],
  "prefetch": [
    {
      "where": {
        "and": [
          { "href_matches": "/catalog/*" },
          { "not": { "selector_matches": ".no-prerender" } }
        ]
      },
      "eagerness": "conservative"
    }
  ]
}
</script>

Notice how this splits the workload cleanly. High-converting pricing, docs, and read-only invoice views prerender on hover so they swap into the viewport instantaneously. Meanwhile, heavier catalog pages fall back to conservative document prefetching on pointerdown, which downloads HTML without running client scripts early.

In addition, prerendering works best when hero images inside those target routes are already compressed properly. When I paired these rules with our Media Condenser WordPress image optimizer on marketing landing pages, background memory usage stayed well below Chrome’s ten-tab speculative cap.

Deferring TypeScript Analytics in the Speculation Rules API

Here’s the hidden telemetry trap. Because prerendered pages execute their top-level JavaScript while still invisible, firing analytics or billing metering inside DOMContentLoaded records visits that never actually happened. Also, standard Largest Contentful Paint observers measure from initial background fetch instead of the user’s click timestamp.

Speculation Rules API Prerender Lifecycle diagram from hover intent to hidden prerender and prerenderingchange activation
Deferring analytics pings while document.prerendering is true prevents phantom pageviews until prerenderingchange fires on click.

Don’t trust raw navigation timestamps. Instead, check document.prerendering first and wait for the W3C prerenderingchange lifecycle event before flushing pageviews or initializing WebSocket subscriptions. Also, subtract activationStart from your LCP entry so your RUM dashboard reports true user-perceived paint latency:

declare global {
  interface Document {
    readonly prerendering?: boolean;
  }
  interface PerformanceNavigationTiming {
    readonly activationStart?: number;
  }
}

export function runWhenPageActivates(task: () => void): void {
  if (typeof document === 'undefined') {
    return;
  }
  if (document.prerendering) {
    document.addEventListener('prerenderingchange', () => task(), {
      once: true,
    });
    return;
  }
  task();
}

export function observeActivatedLcp(
  reportMetric: (lcpMs: number, wasPrerendered: boolean) => void
): void {
  runWhenPageActivates(() => {
    const navEntry = performance.getEntriesByType(
      'navigation'
    )[0] as PerformanceNavigationTiming | undefined;
    const activationOffset = navEntry?.activationStart ?? 0;

    const observer = new PerformanceObserver((entryList) => {
      const entries = entryList.getEntries();
      const lastEntry = entries[entries.length - 1];
      if (!lastEntry) {
        return;
      }
      const adjustedLcp = Math.max(0, lastEntry.startTime - activationOffset);
      reportMetric(Math.round(adjustedLcp), activationOffset > 0);
    });

    observer.observe({ type: 'largest-contentful-paint', buffered: true });
  });
}

Once I shipped observeActivatedLcp across our workspace, two misleading metrics vanished overnight. First, our Stripe usage-dashboard stopped counting hovered invoice tabs as active sessions. Second, our RUM P75 LCP chart reflected the real 38ms visual swap rather than 520ms of idle hover time before the click.

Guarding Backend Endpoints With Sec-Purpose Headers

Check the request headers first. Even with client-side CSS exclusions, bots or dynamically injected anchor tags can still request sensitive routes speculatively. Thankfully, browsers attach Sec-Purpose: prefetch or Sec-Purpose: prefetch;prerender to every speculative HTTP request.

import type { Request, Response, NextFunction } from 'express';

const STATEFUL_PREFIXES = ['/auth/logout', '/billing/export', '/webhooks/test'];

export function guardSpeculativeRequests(
  req: Request,
  res: Response,
  next: NextFunction
): void {
  const secPurpose = String(req.headers['sec-purpose'] ?? '').toLowerCase();
  const isSpeculative = secPurpose.includes('prefetch') || secPurpose.includes('prerender');

  if (!isSpeculative) {
    next();
    return;
  }

  // Reject speculative hits on endpoints with audit logs or rate-limit side effects.
  if (STATEFUL_PREFIXES.some((prefix) => req.path.startsWith(prefix))) {
    res.status(425).set('Cache-Control', 'no-store').end();
    return;
  }

  req.headers['x-speculative-load'] = '1';
  next();
}

Returning HTTP 425 Too Early (or 503) cleanly aborts an unwanted background prerender without showing an error screen to the visitor. When the user actually clicks that link later, the browser falls back to a normal navigation automatically. Similarly, if your route queries large relational tables, pair speculative prefetching with MySQL keyset pagination so hovered requests never trigger slow offset scans.

Prefetch vs Prerender in the Speculation Rules API

Picking between prefetch and prerender comes down to memory overhead versus JavaScript boot time. Therefore, I benchmark both modes against these four criteria before enabling rules on a new route group:

DimensionRule PrefetchRule PrerenderCold Navigation
What DownloadsMain HTML document onlyHTML + CSS + JS + subresourcesEverything after click
JS ExecutionNone until user clicksRuns in hidden background tabRuns after HTML parse
Request HeaderSec-Purpose: prefetchSec-Purpose: prefetch;prerenderStandard navigation headers
Typical P75 LCP210ms – 340ms25ms – 65ms600ms – 1,100ms
Best Route TargetPaginated catalogs & searchTop nav, pricing, docs, next stepLogout, exports, mutations

In short, reserve full prerendering for your highest-probability transitions and use moderate eagerness so mobile data plans stay protected. Meanwhile, keep Chrome DevTools open to Application > Background services > Speculative loads during QA so you can verify whether rules report Ready, Triggered, or Failure before deploying.

Common Developer Questions on the Speculation Rules API

Why do unsupported browsers ignore speculationrules script tags safely?

Browsers that haven’t implemented speculative loading treat <script type="speculationrules"> as an unknown data block and skip parsing it with zero console errors. Consequently, Safari and Firefox users receive standard links automatically, making the feature pure progressive enhancement without needing polyfills or user-agent sniffing.

Why did Chrome cancel my prerender rule in Speculative loads?

Chrome cancels active prerenders when the hidden page calls restricted APIs like window.alert(), requests geolocation permissions, plays unmuted media, or hits device memory pressure. In addition, responses carrying Clear-Site-Data or non-2xx HTTP status codes abort background rendering immediately and revert to normal click navigation.

Anil Mehra on November 30, 2026 SEO & Performance Web Development
previous article
Next article

Leave a comment Cancel reply

Your email address will not be published. Required fields are marked *

About the Author

Anil Mehra

Anil Mehra

Software Engineer · Google AI Certified

Anil Mehra is a Software Engineer specializing in Angular (NgRx, SignalStore, RxJS), React, TypeScript, Node.js, PHP, and MySQL. Holding the Google AI Professional Certificate, he bridges production web architecture with practical AI-powered workflows.

Google AI Professional Certificate official badge

Google AI Professional Certificate

Google · Coursera Credential ↗

About & Consulting · Instagram · LinkedIn

Recent Guides

  • WordPress Block Bindings API guide banner showing custom PHP sources connected to Gutenberg block editor Attributes sidebar
    Block Bindings API in WordPress Plugins: PHP Sources, Editor UI & Batched LoopsDecember 2, 2026
  • WordPress autoloaded options architecture card showing wp_options payload reduction from 1.84 MB to 186 KB and TTFB drop
    WordPress Autoloaded Options: Fix Plugin Bloat, TTFB Spikes & Cache EvictionsDecember 2, 2026
  • claude sonnet 4.5 retirement migration guide banner
    Claude Sonnet 4.5 Retirement Hits Today: How I Migrated Node.js Calls to Sonnet 5.5November 30, 2026
  • speculation rules api instant prerender LCP guide banner
    Speculation Rules API Guide: Cut Route LCP to 38ms Without Phantom AnalyticsNovember 30, 2026

Engineering Topics

  • Angular 13
  • Frontend Development 4
  • Node.js 3
  • PHP & MySQL 2
  • React & TypeScript 2
  • SEO & Performance 2
  • Tech & AI News 4
  • Web Development 21
  • Wordpress Plugins 3
CoreGamix — Full-Stack Engineering & Developer ToolsCoreGamix — Full-Stack Engineering & Developer Tools

contact

support@coregamix.com

© 2026 CoreGamix. All Rights Reserved.  |  About  |  Privacy Policy  |  Terms of Use  |  Contact

Back to top