11ty Plugin: Speculation Rules

npm npm npm npm license license

This plugin adds support for the Speculation Rules API, which allows defining rules by which certain URLs are dynamically prefetched or prerendered based on user interaction.

Demo

Does it work?

Check the network tab in your browser’s developer tools to see if the page is prefetched or prerendered.

More information about the Speculation Rules API can be found here.

More about Debugging speculation rules.

Installation

Install the plugin via npm:

npm install eleventy-plugin-speculation-rules --save-dev

Usage

Once installed, you can use the plugin in your Eleventy configuration file:

const eleventyPluginSpeculationRules = require('@11ty/eleventy-plugin-speculation-rules');
module.exports = function(eleventyConfig) {
    eleventyConfig.addPlugin(eleventyPluginSpeculationRules);
};

Configuration

By default, the plugin will use the following configuration:

{
    mode: 'prerender', // prefetch | prerender
    eagerness: 'moderate', // conservative | moderate | eager
    noPrerenderSelector: '.no-prerender',
    include: [],
    exclude: []
}

You can override the default configuration by passing an object to the plugin:

eleventyConfig.addPlugin(eleventyPluginSpeculationRules, {
    mode: 'prefetch',
    eagerness: 'eager',
    noPrerenderSelector: '.noPrerender',
    include: ['/blog/*'],
    exclude: ['/blog/1']
});

A filter can be used to exclude certain URL paths from being eligible for prefetching and prerendering. Alternatively, you can add the ‘no-prerender’ CSS class to any link (<a> tag) that should not be prerendered.

Speculation Mode

Prerendering will lead to faster load times than prefetching. However, in case of interactive content, prefetching may be a safer choice.

Eagerness

The eagerness setting defines the heuristics based on which the loading is triggered. "Eager" will have the minimum delay to start speculative loads, "Conservative" increases the chance that only URLs the user actually navigates to are loaded.

Browser support

The Speculation Rules API is a new web API, and the functionality used by the plugin is supported in Chromium-based browsers such as Chrome, Edge, or Opera using version 121 or above. Other browsers such as Safari and Firefox will ignore the functionality with no ill effects but will not benefit from the speculative loading. Note that extensions may disable preloading by default (for example, uBlock Origin does this).

Other browsers will not see any adverse effects, however the feature will not work for those clients.

License

MIT License


Fork me on GitHub