speculation-rules-api
26/09/2024 03:16

Speculation Rules API: Instant Page Loading

Optimizing performance with new feature - Speculation Rules API

media

Speculation Rules API

Introduction to the Speculation Rules API

The Speculation Rules API is a groundbreaking feature designed to optimize web performance by preloading and prerendering future navigations. By anticipating user actions, this API significantly improves loading speeds and enhances user experience. This article will delve into how the Speculation Rules API works, its benefits, and how it relates to critical web performance metrics such as Largest Contentful Paint (LCP) and ad loading speeds. Additionally, we will explore its implications for consent management providers and business owners aiming to reduce expenses through optimized content delivery.

Understanding the Speculation Rules API

The Speculation Rules API allows web developers to define rules for preloading and prerendering resources. This helps in speeding up page load times by fetching resources in advance, based on user behavior predictions. It can prefetch HTML pages without loading all subresources or rendering them, thus saving bandwidth and improving performance.

  • Preload (rel=preload): Fetches resources for the current page, ensuring they are available when needed.
  • Prefetch (rel=prefetch): Fetches resources for a future page, making them ready for the next navigation.
  • Prerender (rel=prerender): Fully loads a future page in the background, so it can be displayed instantly when the user navigates to it.

How It Works

The Speculation Rules API can be implemented using JSON within a <script type="speculation rules"> tag. Here are some examples:

Prerender Example

<script type="speculationrules">
  {
    "prerender": [
      {
        "urls": ["next.html", "next2.html"]
      }
    ]
  }
</script>

This script asks the browser to prerender next.html and next2.html. When the user navigates to these pages, they load instantly as the content has already been rendered in the background.

Prefetch Example

<script type="speculationrules">
  {
    "prefetch": [
      {
        "urls": ["next.html", "next2.html"]
      }
    ]
  }
</script>

Prefetching prepares the browser by loading resources for future navigations without rendering them, reducing the time needed for subsequent page loads.

Practical Applications

The API is particularly useful for improving ad loading speeds and managing consent management processes. Faster loading ads mean better user engagement and higher ad relevance. Additionally, by preloading critical resources, businesses can ensure compliance with consent management regulations more efficiently.

  • Ads Loading Speed: By prerendering ad pages, the API ensures that ads load instantly, enhancing the user experience and increasing ad viewability.
  • Consent Management Providers: Preloading consent management scripts ensures that they are ready when needed, minimizing delays in user interactions.

Implementing the Speculation Rules API

Here’s how you can dynamically inject speculation rules using JavaScript:

<script>
  if (HTMLScriptElement.supports?.('speculation rules')) {
    const specScript = document.createElement('script');
    specScript.type = 'speculation rules';
    const specRules = {
      "prerender": [
        {
          "urls": ["/next.html"]
        },
      ],
    };
    specScript.textContent = JSON.stringify(specRules);
    document.body.append(specScript);
  }
</script>

This code snippet dynamically adds speculation rules to the document, enabling preloading and prerendering as needed.

Document Rules

Document rules allow developers to specify which links on a page are eligible for prefetching or prerendering based on URL patterns or CSS selectors. This flexibility helps in targeting specific resources for optimization.

Example Using `href_matches`

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

This script indicates that all same-origin links are eligible for prerendering.

Example Using `selector_matches`

<script type="speculationrules">
  {
    "prerender": [
      {
        "where": {
          "selector_matches": ".prerender"
        }
      }
    ]
  }
</script>

This targets links with the .prerender class for prerendering.

Eagerness Settings

The API supports different eagerness settings to control when resources should be prefetched or prerendered:

  • Conservative: On mouse/pointer down (default for document rules).
  • Moderate: On hover for 200ms or mouse/pointer down.
  • Immediate/Eager: As soon as possible (default for URL list rules).

Mixed Eagerness Example

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

This script uses eager loading for the headline page and moderate settings for other pages.

Availability and Browser Support

The Speculation Rules API is currently supported in Chrome 109 and Edge 109, with no support in Firefox or Safari. In unsupported browsers, the script with type speculation rules is simply ignored, making it backward compatible.

Using CDNs for Speculation Rules

Content Delivery Networks (CDNs) can also inject speculation rules. This can be achieved through:

  • Edge Workers: Injecting JSON scripts at the edge based on server-side analytics.
  • HTTP Headers: Using the Speculation-Rules HTTP header to set rules without altering the page code.

Avoiding Overspeculation

To prevent overspeculation, Chrome limits the number of prefetches and pre-renders based on the eagerness setting. For example, immediate/eager settings allow more prefetches/pretenders compared to moderate/conservative settings.

Handling Large Resources

For large resources such as videos or animations, manual loading can be handled using event listeners:Advanced Techniques and Considerations

<script>
  function afterPrerendering() {
    // start a video/animation
    // fetch large resources
    // connect to a chat server
    // etc.
  }

  if (document.prerendering) {
    document.addEventListener('prerenderingchange', () => {
    afterPrerendering();
  } else {
    afterPrerendering();
  }
</script>

Injecting Speculation Rules via JavaScript

One of the more advanced techniques involves injecting speculation rules dynamically using JavaScript. This can be useful in scenarios where the set of resources to be prefetched or pre rendered may change based on user interactions or other runtime conditions.

Here’s an example of how you can dynamically inject speculation rules:

<script>
  if (HTMLScriptElement.supports?.('speculation rules')) {
    const specScript = document.createElement('script');
    specScript.type = 'speculation rules';
    const specRules = {
      "prerender": [
        {
          "urls": ["/dynamic-next.html"]
        },
      ],
    };
    specScript.textContent = JSON.stringify(specRules);
    document.body.append(specScript);
  }
</script>

This method allows you to add, modify, or remove URLs based on dynamic conditions, ensuring that the rules stay relevant to the user’s current context.

Multiple Speculation Rules

You can define multiple speculation rules on a single page, providing a high degree of flexibility. This is particularly useful for complex websites where different sections might benefit from different prefetching or prerendering strategies.

Example

<script type="speculationrules">
  {
    "prerender": [
      {
        "urls": ["/page1.html"]
      },
      {
        "urls": ["/page2.html"]
      }
    ],
    "prefetch": [
      {
        "urls": ["/page3.html"]
      },
      {
        "urls": ["/page4.html"]
      }
    ]
  }
</script>

In this example, separate rules are defined for prerendering and prefetching, allowing for tailored optimization strategies.

Cost of Using the Speculation Rules API

In most cases, the cost is equivalent to loading an extra iframe, which is generally acceptable given the performance benefits.

Integration with Consent Management Platforms

Consent management platforms (CMPs) are critical for ensuring compliance with privacy regulations such as GDPR. The Speculation Rules API can be integrated with CMPs to enhance user experience by preloading essential scripts and resources.

By preloading consent management scripts, websites can ensure that the consent dialogs and tracking mechanisms are ready when the user interacts with the page, reducing delays and improving compliance.

Performance Metrics and Business Impact

The Speculation Rules API directly impacts key performance metrics such as Largest Contentful Paint (LCP), which measures the time it takes for the main content of a page to become visible. Faster LCP times lead to better user experiences and can improve SEO rankings.

For business owners, implementing the Speculation Rules API can lead to significant cost savings. Faster page loads reduce server load and bandwidth usage, while improved ad loading speeds can increase ad revenue by ensuring higher viewability rates.

Dangers and Caveats of Using the Speculation Rules API

While the Speculation Rules API offers numerous benefits, improper implementation can lead to significant issues. One major risk is the potential for a corrupted browser state. For instance, if the server returns a different state during prerendering, such as when a user logs in or out, the prerendered content might be outdated or incorrect. This can confuse users and degrade their experience. Additionally, triggering prerendering for large resources can lead to excessive network traffic, incurring high costs for site owners, especially if these resources are never used by the user. It's crucial to ensure that prerendering rules are set carefully to avoid unnecessary resource consumption and to monitor the impact on server load and bandwidth usage.

Another critical consideration is managing user interactions during prerendering. If a user starts interacting with the site while prerendering is in progress, it might lead to unexpected behaviors. Therefore, it's essential to test the implementation thoroughly in different scenarios to ensure a smooth user experience.

Integration with Google Publisher Tag (GPT) and Ad Technologies

Integrating the Speculation Rules API with Google Publisher Tag (GPT), Google AdSense, and other ad technologies can significantly enhance the performance of ad loading and display. Here’s how the integration can be beneficial:

Faster Ad Loading

By preloading and prerendering ad slots, the Speculation Rules API ensures that ads are ready to be displayed as soon as the user navigates to a new page. This reduces the time users spend waiting for ads to load, enhancing the overall user experience and increasing the likelihood of ad impressions and clicks.

Improved Ad Relevance

Preloading scripts and resources related to ads allows for quicker execution of ad auctions and serving more relevant ads. For instance, using the Speculation Rules API to preload GPT scripts ensures that ads are targeted based on the latest user data and behavior, which can improve ad relevance and engagement.

Cost Efficiency for Publishers

While preloading and prerendering can increase network traffic, they can also reduce latency and improve ad performance metrics such as viewability and click-through rates. For publishers, this means better monetization and potentially higher revenue. However, it’s important to balance the benefits with the potential increase in bandwidth costs. Implementing effective rules to avoid unnecessary preloading of large, infrequently used resources is essential.

Infinite Scroll and Ad Loading

Using an infinite scroll solution on an article page, where new articles with vertical or horizontal banners load as the user scrolls, can also benefit from the Speculation Rules API. Here’s how you can integrate the API to optimize ad loading in an infinite scroll setup:

Implementation for Infinite Scroll

<script>
  let articleCounter = 1;

  function loadNextArticle() {
    articleCounter++;
    const nextArticleURL = `/article${articleCounter}.html`;

    if (HTMLScriptElement.supports?.('speculationrules')) {
      const specScript = document.createElement('script');
      specScript.type = 'speculationrules';
      const specRules = {
        "prefetch": [
          {
            "urls": [nextArticleURL]
          }
        ],
        "prerender": [
          {
            "urls": [nextArticleURL]
          }
        ]
      };
      specScript.textContent = JSON.stringify(specRules);
      document.body.append(specScript);
    }

    // Load the next article (simplified for illustration purposes)
    fetch(nextArticleURL)
      .then(response => response.text())
      .then(html => {
        const articleContainer = document.createElement('div');
        articleContainer.innerHTML = html;
        document.body.append(articleContainer);
      });
  }

  window.addEventListener('scroll', () => {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight)       
    {
      loadNextArticle();
    }
  });
</script>

Catch Metrics is the leading solution to help solve ad stack performance problems.Get in touchto learn more from our experts

Get Started Today

Sign up for a demo or contact our team to learn more about how Catch Metrics can help you achieve your goals. As part of all demos we offer a free Ad Speed Audit and ROI modelling exercise to help you understand how your Ad speed is impacting your revenues.