This article demonstrates the use of Speculation Rules API.
What are speculation rules?
The speculation rules tell the browser which page is likely to be the next one the visitor goes to. The browser will either download the page's content (prefetch) or render it in advance (prerender).
The sample use cases include the hero banners on an e-commerce website or the headlines on a news portal. These are likely to be clicked by the visitors, and with prefetch or prerender, it is possible to show them the content as soon as we can.
How do we deliver speculation rules?
Option 1: Via an inline script
<script type="speculationrules">
{
"prefetch": [
{
"urls": ["/posts/1", "/posts/2"],
"eagerness": "eager,
"referrer_policy": "no-referrer"
}
]
}
</script>
Option 2: Via the "Speculation-Rules" HTTP header
response.headers['Speculation-Rules'] = '"/speculation_rules"'
The URL endpoint should return the rules similar to option 1.
It is important to set the MIME type to "application/speculationrules+json".
response.headers['Content-Type'] = 'application/speculationrules+json'
How do we know the rules are effective?
1) Check the browser support. Not all browsers implement this feature at the time this article is written.
2) Check the developer tool to see if the prefetch or prerender is applied. For example in Google Chrome, it is available in the "Application" tab.
Notes
1) You have to carefully plan the rules, as excessive rules might consume unnecessary infrastructure and bandwidth.
2) You can set the "eagerness" setting to prevent wastage. (For example, a "moderate" setting only applies the rule when the user mouse over the target link for more than 200ms.)
3) Major analytics tools (such as Google Analytics) already filter the traffic from speculation rules, to avoid counting these traffic as actual visits. If you are using custom-made analytics tools, you should check if they already handle this kind of traffic.