Prerender pages with Speculation Rules
You can leverage Speculation Rules API to improve the performance of Multi Page Apps (MPA) by prefetching or prerendering future navigations. This API promises a nearly-instant load of URLs that you specify in a special JSON structure, along with other rules that define how and when to trigger each speculative loading type. By identifying and prefetching pages your users might want to access next, you can significantly impact important performance KPIs, such as Largest Contentful Paint (LCP) or Cumulative Layout Shift (CLS).
Speculation Rules API and other Akamai products
Speculation Rules API also works well with Dynamic Site Acceleration, Web Application Protector, and Kona Site Defender. You can use instructions below to implement prerendering in all supported products.
Before you begin
- Currently, Speculation Rules API is only supported by Chromium-based browsers. Other browsers ignore any speculation rules.
- If you want to learn more about available options, debug possibilities, potential risks and nuances of this API, see Google's Web Platform documentation. As this is still an experimental technology, you should exercise caution when adopting it. Akamai isn't responsible for any loss if you choose to incorporate the Speculation Rules API.
- Document Rules still require a specific opt in with Origin Trials for versions lower than 121.
Add speculation rules to your pages
To communicate the JSON structure containing speculation rules to the browser with Akamai, you can either use Property Manager behaviors, or embed it directly in the HTML with EdgeWorkers.
Implementation through Property Manager has a few additional benefits over the EgdeWorkers approach:
- Cache efficiency:
- Allows A/B testing without cache poisoning.
- Purging speculation rules does’t evict cached HTML.
- Edge logic without delaying HTML – flexible implementation of speculation rules based on user location, connection or other criteria.
Method 1: Reference speculation rules in the HTTP response header
-
In the Property Manager Editor, in the Property Configuration Settings panel, click Add Rule and select a blank rule template. This rule will add speculation rules to a HTTP response header on all pages managed by your property.
-
In the Criteria panel, click +Match and from the dropdown, select File extension.
-
Set the operator to is one of and enter these comma-separated extensions:
html
,htm
,php
,jsp
,asp
,EMPTY_STRING
-
In the Behaviors panel click +Behavior and select Modify Outgoing Response Header. Click Insert Behavior.
-
Set the behavior options:
- Set Action to Add.
- Set Select Header Name to Other.
- In Custom Header Name, enter:
Speculation-Rules
- In the Header Value, enter:
“/speculationrules.json”
-
Click Add Rule and select another blank rule template. This rule will define how to respond to requests for the JSON file.
-
In the Criteria panel, click +Match and from the dropdown, select Path.
-
Set the operator to matches one of and enter this path:
/speculationrules.json
-
In the Behaviors panel click +Behavior and select Construct Response. Click Insert Behavior.
-
Set the behavior options:
- Set Status to On.
- In Response Body, enter the JSON structure specifying the speculation rules you want to apply, leaving out the
<script type=speculationrules> </script>
wrapping. For example:{ "prefetch":[{"source":"document","where":{"selector_matches":"nav a, a.article"},"eagerness":"moderate"}], "prerender":[{"source":"document","where":{"selector_matches":"nav a, a.article"},"eagerness":"conservative"}] }
- Set Response Code to 200 OK.
- Set Force Cache Eviction to Off.
- Set Ignore for Purge requests to Off.
-
In the Behaviors panel click +Behavior and select Construct Response. Click Insert Behavior.
-
Set the behavior options:
- Set Action to Add.
- Set Select Header Name to Content-Type.
- In Header Value, enter:
application/speculationrules+json
You can skip adding the Construct Response behavior if you’d prefer to reference the JSON structure as an external resource and host the
speculationrules.json
file on your origin server, Akamai NetStorage, or Linode Object Storage.
-
In the Behaviors panel click +Behavior and select Construct Response. Click Insert Behavior.
-
Set the behavior options:
- Set Action to Add.
- Set Select Header Name to Access-Control-Allow-Origin.
- In Header Value, enter:
*
(or stricter).
-
Continue configuring your property. Then you can finalize it, test it, and go live to deliver your site.
Method 2: Embed speculation rules in HTML using Edge Workers
You can insert the speculation rules directly into your page’s HTML using Akamai EdgeWorkers. Use the native html-rewriter 1 library to modify the response body and append <script type=speculationrules>${RULES}</script>
to the <body>
element. Refer to the EdgeWorkers documentation for more details on how to transform HTML documents.
Example:
import { HtmlRewritingStream } from 'html-rewriter';
import { httpRequest } from 'http-request';
import { createResponse } from 'create-response';
export async function responseProvider(request) {
…
let rewriter = new HtmlRewritingStream();
const RULES = getSpeculationRules(request);
rewriter.onElement('body', el => {
el.append(`<script type=speculationrules>${RULES}</script>`);
});
return httpRequest(originURL,options).then(response => {
return createResponse(
response.status,
headers,
response.body.pipeThrough(rewriter)
)
})
}
function getSpeculationRules(request){
let rules = {} //Read locally, fetch or read from EKV
return rules;
}
Updated 10 months ago