HiveBrain v1.2.0
Get Started
← Back to all entries
snippethtmlTip

A first look at the Speculation Rules API

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
speculationfirstlookrulesapithehtml

Problem

If page performance is important to you, you may already be familiar with resource prefetching, using a <link> tag and the rel="prefetch" attribute. In fact, we've covered this topic in the past, so, if you're not familiar, I'd suggest starting there.
@Quick refresher
<baseline-support featureId="speculation-rules">
</baseline-support>
Prefetching individual links, however, is often tedious, even without the hassle of deciding which links needs prefetching. This is where the currently experimental Speculation Rules API comes in.

Solution

<!-- Prefetch all local pages -->
<script type="speculationrules">
{
  "prefetch": [{
    "where": {
      "href_matches": "/*"
    },
    "eagerness": "moderate"
  }]
}
</script>


<baseline-support featureId="speculation-rules">
</baseline-support>
Prefetching individual links, however, is often tedious, even without the hassle of deciding which links needs prefetching. This is where the currently experimental Speculation Rules API comes in.
> [!WARNING]
>
> This API is, as stated, currently experimental. This means it's very likely to change before it becomes stable and any information provided here may become outdated. Always refer to the official documentation for more information.

Code Snippets

<!-- Prefetch all local pages -->
<script type="speculationrules">
{
  "prefetch": [{
    "where": {
      "href_matches": "/*"
    },
    "eagerness": "moderate"
  }]
}
</script>
<script type="speculationrules">
{
  "prefetch": [{
    "where": {
      "and": [
        { "href_matches": "/*" },
        { "not": {"href_matches": "/wp-admin"}},
        { "not": {"href_matches": "/*\\?*(^|&)add-to-cart=*"}},
        { "not": {"selector_matches": "[rel~=nofollow]"}}
      ]
    }
  }]
}
</script>
<script type="speculationrules">
{
  "prefetch": [
    {
      "urls": ["/home", "/about", "/contact"]
    }
  ]
}
</script>

Context

From 30-seconds-of-code: speculation-rules-api-first-look

Revisions (0)

No revisions yet.