Skip to main content

Using the Speculation Rules API to Improve Performance

Posted on
Contents

If you have a multi-page site and want to improve performance when navigating between pages, I recommend using speculation rules to prefetch and render pages on hovering over a link. This can substantially reduce load times and improve the user experience.

I’ve added it to this site and switching between pages is now even faster. Here’s how you can implement it - just stick this script in the <head> of your HTML and you’re good to go!

<script type="speculationrules">
{
  "prerender": [{
    "where": {
      "href_matches": "/*"
    },
    "eagerness": "moderate"
  }]
}
</script>

The eagerness - moderate setting means that this performs speculations if you hold the pointer over a link for 200 milliseconds (or on the pointerdown event if that is sooner, and on mobile where there is no hover event).

Speculation Rules are currently only available in Chrome/Edge and other Chromium-based browsers, so it doesn’t work in Safari or Firefox, however you can conditionally load the instant.page script. It’s only about 1 KB and provides similar functionality across all other browsers.

<script>
  // Fallback to instant.page for browsers that don't support speculation rules
  if (!(HTMLScriptElement.supports && HTMLScriptElement.supports('speculationrules'))) {
    const script = document.createElement('script');
    script.type = 'module';
    script.src = 'https://instant.page/5.2.0';
    script.fetchPriority = 'low';
    script.defer = true;
    document.head.appendChild(script);
  }
</script>

Unfortunately, ad blockers can interfere with speculation rules (the setting to disable preloading is checked by default on uBlock Origin and Privacy Badger), so users with ad blockers may not benefit from this feature.

You might also like