SJ (Scott Jehl)

Just Speculating: You May Not Need a SPA framework

photo of scott jehl profile headshot

By Scott Jehl

If you follow Web Performance topics closely, perhaps you've heard about Speculation Rules, a new browser API that aims to improve page-to-page navigation speed for multi-page websites (aka normal websites). While not yet a W3C standard, Speculation Rules are already fully supported in the stable version of Chromium-based browsers. That means you can use them today to improve the time it takes users to navigate from particular pages to another, and it'll work for folks who use Chrome, Edge, and others while not impacting the experience in browsers that don't yet support it.

As a fan of technologies that aim to help reduce our reliance on JavaScript for critical front-end infrastructure, I'm excited for the potential that Speculation Rules offers. Page-to-page navigation speed is often touted as a key reason that teams decide to build sites using Single-Page-App JavaScript frameworks, but in order to reap the benefits those frameworks provide, there's often an upfront performance cost.

I would uh, speculate that Speculation Rules used in combination with Cross-Document View Transitions will offer a preferable and elegant approach to mimicking all of that with JavaScript. It may be a minute before we can rely on these things across browsers, but they happen to be built in ways that are harmless to opt-into already, which is great.

How SR works, in brief

The way Speculation Rules work is similar in some ways to existing standards like resource hints (you know, rel=preload, prerender, preconnect, etc), though the format is more robust and expressive, and formatted as JSON. The rules can be delivered via a script element with a type of speculationrules, like this example from MDN:

<script type="speculationrules">
  {
    "prerender": [
      {
        "where": {
          "and": [
            { "href_matches": "/*" },
            { "not": { "href_matches": "/logout" } },
            { "not": { "selector_matches": ".no-prerender" } }
          ]
        }
      }
    ],
    "prefetch": [
      {
        "urls": ["next.html", "next2.html"],
        "requires": ["anonymous-client-ip-when-cross-origin"],
        "referrer_policy": "no-referrer"
      }
    ]
  }
</script>

Or perhaps preferably, via an HTTP header that references a JSON file containing something like the example above, like this:

Speculation-Rules: "/rules/prefetch.json"

Find Out More!

I hope to see more experimentation and broader browser support for Speculation Rules in the near future. For more on the topic, I'd recommend checking out MDN's great documentation of the Speculation Rules API.

And also, don't miss Barry Pollard's talk, From fast loading to instant loading, from Google I/O, which I'll embed here below: