Performance PHP Intermediate

Tune or Turn Off Speculative Loading

Make WordPress prerender pages as visitors hover over links for near-instant navigation, or turn speculative loading off.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 10 lines
add_filter( 'wp_speculation_rules_configuration', function ( ?array $config ): ?array {
	// Prerender the next page when a visitor hovers over a link.
	return [
		'mode'      => 'prerender',  // 'prefetch' only downloads the HTML; 'prerender' fully loads the page.
		'eagerness' => 'moderate',   // 'conservative' waits for a click; 'moderate' starts on hover.
	];

	// To turn speculative loading off completely, return null instead:
	// return null;
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Since WordPress 6.8, sites add speculation rules that let supporting browsers start loading the next page before the visitor clicks. The default is cautious: it only prefetches the page when the link is pressed. This snippet lets you choose a faster setting, or turn it off.

How it works

The wp_speculation_rules_configuration filter returns the mode and eagerness WordPress uses to build its speculation rules. prerender loads and renders the whole page in the background, so it appears instantly when clicked. moderate starts when the pointer rests on a link for a moment.

WordPress automatically excludes wp-admin, login links and URLs with query strings, which are more likely to change something.

Things to watch

  • Prerendering runs the page’s JavaScript, including analytics, before the visitor arrives. Most analytics tools handle this correctly, but check yours.
  • Pages that change state on load, like “add to cart” links, should be excluded with the wp_speculation_rules_href_exclude_paths filter.
  • Only Chromium-based browsers support speculation rules today. Others ignore them.

How to test it

View your page source and find the &lt;script type="speculationrules"&gt; tag near the bottom. It should list prerender with moderate eagerness.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only