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

  1. 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.

  2. In the Criteria panel, click +Match and from the dropdown, select File extension.

  3. Set the operator to is one of and enter these comma-separated extensions: html, htm, php, jsp, asp, EMPTY_STRING

  4. In the Behaviors panel click +Behavior and select Modify Outgoing Response Header. Click Insert Behavior.

  5. Set the behavior options:

    1. Set Action to Add.
    2. Set Select Header Name to Other.
    3. In Custom Header Name, enter: Speculation-Rules
    4. In the Header Value, enter: “/speculationrules.json”
  6. Click Add Rule and select another blank rule template. This rule will define how to respond to requests for the JSON file.

  7. In the Criteria panel, click +Match and from the dropdown, select Path.

  8. Set the operator to matches one of and enter this path: /speculationrules.json

  9. In the Behaviors panel click +Behavior and select Construct Response. Click Insert Behavior.

  10. Set the behavior options:

    1. Set Status to On.
    2. 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"}] 
      }
      
    3. Set Response Code to 200 OK.
    4. Set Force Cache Eviction to Off.
    5. Set Ignore for Purge requests to Off.
  11. In the Behaviors panel click +Behavior and select Construct Response. Click Insert Behavior.

  12. Set the behavior options:

    1. Set Action to Add.
    2. Set Select Header Name to Content-Type.
    3. 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.

  13. In the Behaviors panel click +Behavior and select Construct Response. Click Insert Behavior.

  14. Set the behavior options:

    1. Set Action to Add.
    2. Set Select Header Name to Access-Control-Allow-Origin.
    3. In Header Value, enter: * (or stricter).
  15. 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;
}