Skip to main content

Speculation Rules API Production Implementation: Boost LCP

LearnWebCraft Team
12 min read
Speculation Rules APILCP optimizationCore Web Vitalsweb performance

Introduction to LCP and Performance

We have all been there. You click a link, and then... you wait. You stare at a white screen. Maybe a spinner appears, or maybe a header loads, but the main content—the "meat" of the page—takes just a second too long to show up. In that split second, frustration builds. If it takes too long, you might just hit the back button.

In the world of web development, we measure this "waiting time" with a metric called Largest Contentful Paint (LCP).

LCP is essentially a stopwatch that starts when a user clicks a link and stops when the largest block of content (usually a hero image or a big paragraph of text) is fully visible on the screen. It is one of the three Core Web Vitals that Google uses to judge the health of your site. A good LCP score (under 2.5 seconds) makes your site feel snappy and professional. A bad one makes it feel sluggish.

That is exactly where the Speculation Rules API comes in. It is a game-changer that allows us to boost LCP scores not by making resources smaller, but by predicting the future.

What is the Speculation Rules API?

Imagine you are at a restaurant. In a normal scenario, you sit down, look at the menu, decide what you want, call the waiter, place your order, and then wait for the kitchen to cook it. That waiting time is your LCP.

Now, imagine a scenario where the waiter is a mind reader. As you walk toward a table, the waiter knows you are going to order the steak. The kitchen starts cooking it before you even sit down. By the time you snap your fingers to order, the plate is already being placed in front of you. Zero wait time.

The Speculation Rules API is that mind-reading waiter for your browser.

It is a modern JavaScript feature that lets you tell the browser which pages the user is likely to visit next. Based on these "speculations," the browser can do one of two things in the background:

  1. Prefetch: Download the resources (HTML, CSS, JS) for the next page and store them in the cache. When the user clicks, the network part is already done.
  2. Prerender: This is the heavy hitter. The browser not only downloads the resources but also renders the entire page in an invisible background tab. It runs the JavaScript, paints the pixels, and gets everything ready. When the user clicks, the browser simply swaps the current view for the hidden one instantly.

Previously, we used <link rel="prefetch"> tags to do this, but they were limited and hard to control. The Speculation Rules API uses a simple JSON structure to give you granular control over exactly what gets loaded and when.

How Speculation Rules API Boosts LCP

To understand why this API is so powerful for LCP optimization, we need to look at what usually happens during a page load.

When a user navigates to a new page, the browser has to go through a "Critical Rendering Path":

  1. DNS Lookup: Find the server address.
  2. TCP Handshake: Connect to the server.
  3. Request/Response: Ask for the HTML and wait to get it.
  4. Parsing: Read the HTML, find CSS and JS links.
  5. Rendering: Calculate layout and paint pixels.

LCP is the sum of all these steps.

When you use the Speculation Rules API to prerender a page, all of these steps happen while the user is still reading the current page.

Because the heavy lifting is done in the background, when the user finally clicks the link, the "Load Time" is effectively near zero. The "Largest Contentful Paint" is already painted. It is waiting in memory. The switch is instantaneous.

In many tests, this can take an LCP of 1.5 seconds or 2 seconds and drop it down to virtually 0 seconds (from the user's perspective). It is one of the few performance optimizations that can make a website feel like a native mobile app.

Implementing Speculation Rules API: A Practical Guide

Implementing this might sound complex, but it is surprisingly developer-friendly. You don't need to install heavy libraries or rewrite your backend. You just need to add a specific <script> tag to your HTML.

The API relies on JSON defined inside a script tag with the type speculationrules.

Here is the general structure:

<script type="speculationrules">
{
  "prerender": [
    {
      "source": "list",
      "urls": ["/next-page", "/another-page"]
    }
  ]
}
</script>

The Breakdown

  • <script type="speculationrules">: This tells the browser, "Hey, this isn't regular JavaScript. This is a set of instructions for background loading."
  • "prerender": This indicates we want to fully render the page (highest performance boost). You could also use "prefetch" here if you want to save data but still speed things up.
  • "source": "list": This tells the browser we are going to provide a specific list of URLs.
  • "urls": The actual paths you want to load.

Basic Prerendering with Speculation Rules

Let's look at a real-world example. Suppose you have a blog, and you know that 80% of users who finish an article click the "Next Article" button. You want that transition to be instant.

Here is how you would implement it on your blog post template:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Awesome Blog</title>
    
    <!-- Speculation Rules for the next article -->
    <script type="speculationrules">
    {
      "prerender": [
        {
          "source": "list",
          "urls": ["/blog/how-to-optimize-images"]
        }
      ]
    }
    </script>
</head>
<body>
    <h1>Welcome to the current article</h1>
    <p>Lots of interesting content here...</p>
    
    <!-- The link that matches the speculation rule -->
    <a href="/blog/how-to-optimize-images">Read Next: Image Optimization</a>
</body>
</html>

When a user lands on this page, Chrome (or any supporting browser) reads that script. It quietly opens /blog/how-to-optimize-images in a hidden background process. It downloads the HTML, CSS, and images for that page.

When the user clicks the link, boom—it's there. No white flash. No waiting.

Advanced Usage and Configuration

Listing every URL manually is tedious and hard to maintain. Thankfully, the Speculation Rules API offers a smarter way to target links: Document Rules.

Instead of a hardcoded list ("source": "list"), we can use "source": "document". This tells the browser to look at the links currently in the HTML of the page and pick which ones to preload based on criteria like CSS selectors or href patterns.

This is where the magic of eagerness comes in.

The eagerness Setting

You don't want to prerender every link on a page; that would crash the user's browser and eat up their data plan. The eagerness property controls when the speculation starts.

  1. immediate: Starts loading as soon as the current page loads. Use this only for links you are 99% sure the user will visit (like a "Next Step" in a checkout wizard).
  2. conservative: Starts loading when the user clicks or touches the link (but before the navigation fully commits). This is a safe baseline.
  3. moderate: This is the sweet spot for most developers. It starts loading when the user hovers over the link for more than 200 milliseconds. This is a strong signal of intent, giving the browser enough time to fetch data before the click happens.

Example: The "Moderate" Approach

Here is an advanced configuration that targets all links that start with /products/ and uses the "moderate" eagerness setting (hover-triggered).

<script type="speculationrules">
{
  "prerender": [
    {
      "source": "document",
      "where": {
        "and": [
          { "href_matches": "/products/*" },
          { "not": { "href_matches": "/products/logout" } }
        ]
      },
      "eagerness": "moderate"
    }
  ]
}
</script>

In this example:

  • We use "source": "document" to scan the page.
  • The where clause filters links. It looks for any link pointing to /products/....
  • We added a not clause to exclude the logout link (you definitely don't want to prerender a logout action!).
  • eagerness: "moderate" ensures we only load the heavy page when the user hovers over the product link.

Monitoring and Debugging

You have added the script, but how do you know it is working? Since prerendering happens in the background, you won't see it happening in the main window.

For this, we turn to Chrome DevTools.

  1. Open your website in Chrome.
  2. Right-click anywhere and select Inspect (or press F12).
  3. Navigate to the Application tab in the top panel.
  4. In the left sidebar, scroll down until you see the Background Services section.
  5. Click on Speculative Loads.

Here, you will see a dashboard of your speculation rules. It will show:

  • Rule Status: Whether your JSON syntax is valid.
  • Speculations: A list of URLs the browser is currently prefetching or prerendering.
  • Status: It will say "Ready" if the page is fully rendered in the background, or "Failure" if something went wrong.

If you see a "Failure," click on it to see the reason. Common reasons include the server returning a 404 or 500 error, or the page attempting to play audio automatically (which browsers block in the background).

Best Practices for Using Speculation Rules

With great power comes great responsibility. Prerendering is resource-intensive. It uses the user's battery, CPU, and data. If you abuse it, you might slow down the current page while trying to speed up the next one.

Here are some golden rules to follow.

1. Don't Prerender Everything

Never apply a blanket rule to prerender every link on the page. Only target high-probability links. If you have a navigation menu with 20 items, do not prerender all of them. Use eagerness: "moderate" so you only load what the user is actually interested in (hovering over).

2. Consider Mobile Data

Mobile users often have limited data plans and less powerful processors. Be mindful of this. While the API has some built-in safeguards (it won't prerender if the user is in "Data Saver" mode), it is best to be conservative on mobile views.

3. Avoid "State-Changing" URLs

Do not prerender links that perform actions, such as "Add to Cart," "Logout," or "Delete Account." Prerendering executes the JavaScript on that page. If simply visiting a URL triggers an action, prerendering it will trigger that action without the user's consent. Always use proper RESTful methods (POST/DELETE) for actions, which the API naturally ignores, but be careful with GET requests that have side effects.

Potential Challenges and Considerations

While the Speculation Rules API is fantastic, there are a few "gotchas" you need to be aware of.

The Analytics Problem

This is the biggest challenge. Because prerendering runs the JavaScript on the target page, your analytics scripts (like Google Analytics) might run before the user actually sees the page.

If the user hovers, the page prerenders (analytics counts a page view), but then the user decides not to click... your analytics data is now inaccurate. You have a "ghost" visit.

To fix this, you need to update your analytics code to check if the document is currently prerendering.

if (document.prerendering) {
  // Wait until the page is actually activated (viewed)
  document.addEventListener("prerenderingchange", () => {
    // Now send the analytics event
    sendAnalyticsData();
  }, { once: true });
} else {
  // Standard load, send immediately
  sendAnalyticsData();
}

Browser Support

As of late 2024, the Speculation Rules API is primarily supported in Chromium-based browsers (Chrome, Edge, Opera). Safari and Firefox have not fully adopted it yet.

However, this is okay! This API is a progressive enhancement. If a browser doesn't understand the <script type="speculationrules"> tag, it simply ignores it. Chrome users get a lightning-fast experience, and other users get the standard experience. It won't break your site.

Cross-Origin Restrictions

Prerendering works best for pages on the same domain (same-origin). If you try to prerender a link to an external website (like example.com to google.com), the browser is much stricter due to privacy concerns. It usually requires the target site to opt-in via specific HTTP headers. For beginners, stick to prerendering your own internal pages.

Conclusion

The Speculation Rules API represents a shift in how we think about web performance. We are moving from "optimizing the load" to "eliminating the load."

By implementing simple JSON rules, you can dramatically improve your LCP scores and, more importantly, the perceived performance for your users. A site that reacts instantly builds trust and keeps users engaged.

Start small. Pick your most important user journey—maybe the flow from your homepage to your top product, or from a blog list to a blog post. Add a simple speculation rule, set the eagerness to "moderate," and watch the magic happen in Chrome DevTools.

The web is getting faster, and with tools like this, your site can lead the pack.

Frequently Asked Questions

What happens if the user doesn't click the prerendered link? The browser eventually discards the prerendered page to free up memory. It's a "waste" of resources in that specific instance, which is why using eagerness: "moderate" (hover-triggered) is recommended to ensure high intent before loading.

Does this replace <link rel="prefetch">? Yes, essentially. The Speculation Rules API is the modern, more powerful replacement for the older prefetch tags. It offers more control and better performance features like full prerendering.

Will this slow down the current page? Browsers are smart. They assign a lower priority to speculation requests compared to the resources needed for the current page. However, if you prerender too many pages at once, it can still consume CPU and battery, so use it wisely.

Is it safe to use on e-commerce sites? Yes, but be careful with dynamic content. Ensure your analytics are configured to handle prerendering (as discussed above) and avoid prerendering URLs that modify the cart or user state via GET requests.

Related Articles