JavaScript
min read
Last update on

Solving performance challenges with the Speculation API: a deep dive

Solving performance challenges with the Speculation API: a deep dive
Table of contents

Web applications today are expected to respond instantly. Even minor lags between user action and content load can lead to user drop-off, higher bounce rates, and lost engagement.

At QED42, we’ve been experimenting with several ways to address these challenges, and one technology that has stood out is the Speculation API. This powerful tool has allowed us to solve critical performance bottlenecks, delivering faster and more seamless experiences to our users.

This article breaks down the performance bottlenecks we faced, why traditional methods fell short, and how the Speculation API helped us solve them—both in Vanilla JavaScript and in Next.js 15+ environments.

The problem we solved

Challenge: slow navigation between pages

One of the most common performance issues we faced was slow navigation between pages. In a typical web application, when a user clicks a link, the browser must fetch the new page’s resources, such as HTML, CSS, and JavaScript. This process can take time, especially on slower networks or for pages with heavy assets. The delay between clicking a link and seeing the new page load often led to a poor user experience.

Traditional solutions and their limitations

To address this, we initially relied on traditional techniques like <link rel="prefetch"> and <link rel="preload">. While these methods helped to some extent, they had significant limitations:

  • Static and inflexible: These techniques required us to manually specify which resources to preload, making it difficult to adapt to dynamic user behaviour.
  • Overfetching: Preloading unnecessary resources wastes bandwidth and sometimes even slows down the application.
  • Complexity with service workers: While service workers offered more control, they required significant setup and maintenance, making them impractical for simpler use cases.

The breakthrough: Speculation API

  • Dynamic preloading based on user behaviour: The Speculation API enabled us to preload resources only when they were likely to be needed. For example, when a user hovers over a link, we can prefetch the target page’s resources in the background. This ensures that the page loads almost instantly when the user clicks the link.
  • Bandwidth efficiency: By preloading resources dynamically, we avoided overfetching and ensured that only the most critical resources were loaded. This was particularly important for users on slower networks or limited data plans.
  • Seamless integration: It is lightweight and easy to integrate into existing projects. It doesn’t require complex setups like service workers, making it accessible for both small and large applications.

Implementation: how we did it

To demonstrate how we implemented the Speculation API, we’ll walk through examples in both Vanilla JavaScript and Next.js 15+. These examples reflect real-world scenarios where we used the API to solve performance challenges.

Vanilla JavaScript implementation

In one of our projects, we used the Speculation API to preload the next page when a user hovers over a link. Here’s how we did it:

// Check if the browser supports the Speculation API
if ('speculationRules' in document) {
  // Define a rule to preload the next page when a link is hovered
  const rule = {
    source: "list",
    urls: ["/next-page.html"],
    actions: ["prefetch"],
  };

  // Apply the rule
  document.speculationRules.add(rule);
}

Impact

  • Reduced navigation latency: By prefetching the next page on hover, we reduced the time it took to load the page when the user clicked the link.
  • Improved user experience: Users reported faster and smoother transitions between pages, leading to higher engagement.

Next.js 15+ implementation

In a Next.js 15+ project, we used the Speculation API to preload critical pages during the initial page load. Here’s how we implemented it:

Enable the Speculation API in next.config.js:

module.exports = {
  experimental: {
    speculationRules: true,
  },
};


Add Speculation rules in a component:

import { useEffect } from 'react';

export default function Home() {
  useEffect(() => {
    if ('speculationRules' in document) {
      const rule = {
        source: "list",
        urls: ["/about", "/contact"],
        actions: ["prefetch"],
      };
      document.speculationRules.add(rule);
    }
  }, []);

  return (
    <div>
      <h1>Welcome to the Home Page</h1>
      <a href="/about">About Us</a>
      <a href="/contact">Contact Us</a>
    </div>
  );
}

Impact

  • Faster page transitions: By prefetching the /about and /contact pages during the initial load, we ensured that these pages loaded almost instantly when users navigated to them.
  • Scalable solution: The implementation was lightweight and scalable, making it easy to extend to other pages and components.

Comparing the Speculation API to alternatives

While the Speculation API has been a game-changer for us, it’s important to understand how it compares to other solutions:

Feature Speculation API <link rel="prefetch"> Service Workers
Dynamic Preloading Yes No Yes
Granular Control High Low High
Ease of Implementation Easy Easy Complex
Bandwidth Efficiency High Medium High

Lessons learned and best practices

Through our experience with the Speculation API, we’ve identified several best practices:

  1. Focus on critical paths: Use the API to preload resources that are most likely to be needed, such as the next page in a user flow.
  1. Test across networks: Ensure your implementation works well on both fast and slow networks.
  1. Monitor performance: Use tools like Lighthouse and Web Vitals to measure the impact of your optimizations.
  1. Graceful degradation: Ensure your application works even in browsers that don’t support the Speculation API.

Why the Speculation API matters

The broader landscape of web performance

Web performance optimization is a multi-faceted challenge that involves reducing load times, minimizing resource usage, and improving user experience. Techniques like lazy loading, code splitting, and caching have been widely adopted to address these challenges. However, these methods often require significant effort and can be difficult to implement effectively.

The Speculation API represents a shift towards native, browser-level optimizations. By providing developers with tools to preload resources dynamically, it reduces the need for complex workarounds and enables more efficient performance optimizations.

The future of predictive loading

As web applications become more dynamic and user-centric, the ability to predict and preload resources based on user behaviour will become increasingly important. The Speculation API is a step in this direction, offering a glimpse into the future of web performance optimization.

Compatibility and adoption

While the Speculation API is still in its early stages, it is supported by modern browsers like Chrome and Edge. As adoption grows, we expect to see more widespread use and further enhancements to the API.

Conclusion

The Speculation API has been a transformative tool for us.Enabling dynamic, behaviour-driven preloading, has allowed us to solve critical performance challenges and deliver faster, more seamless experiences to our users. 

Whether you’re working with Vanilla JavaScript or Next.js 15+, the Speculation API offers a lightweight and powerful solution to optimize your web application’s performance.

If you’re facing similar performance challenges, we highly recommend exploring the Speculation API. Its ease of use, combined with its powerful capabilities, makes it a valuable addition to any developer’s toolkit.


Written by
Editor
Ananya Rakhecha
Tech Advocate