[ad_1]
Today’s web pages are packed with images, videos, and other cool stuff, sometimes making them load slowly.
Want to make your pages faster? Try prerendering or prefetching them before users open them. This way, your content is ready to go, giving visitors a seamless and speedy browsing experience. The Speculative Loading API resolved a previously unsolved issue. In the past, solutions focused on prefetching resources such as JavaScript and CSS but did not involve prerendering the entire webpage.
At the beginning of 2024, Adam Silverstein from Google mentioned that the WordPress Performance team is developing a plugin to enable the Speculation Rules API.
“We have already implemented a module in the Performance Lab plugin that uses the Speculation Rules API. It’s a basic implementation where we use the conservative approach, prerending pages on hover. […] The goal here is to enable testing. We’d like to merge something in the core, but we need people to be able to test it first.”
In April 2024, WordPress officially released Speculative Loading, a performance plugin that supports the Speculation Rules API.
Table of Content
What is Speculation Rules API?
The Speculation Rules API allows developers to define pre-rendering and pre-fetching content rules.
This helps improve page load times by loading pages or resources in the background before a user navigates to them.
The API controls which pages should be pre-rendered and under what conditions, allowing for more efficient resource use and a smoother user experience.
Speculative Loading Mechanisms
1. Prefetching instructs the browser to download the main content of the referenced pages without fetching their subresources. This speeds up the loading time when a user navigates to a prefetched page.
Tag: <link rel=”prefetch”…>
2. Prerendering goes a step further by instructing the browser to fetch, render, and load all content, including subresources and JavaScript, into an invisible tab, which will load in about 50 milliseconds when the user goes to it.
Tag: <link rel=”prerender”…>
Our Managed WordPress Hosting with PHP X-Ray improves the performance of your websites and offers a 99.9% uptime guarantee. Focus on creating; we’ll handle the speed.
System Requirements for Using Speculative Loading API in WordPress
Server Resources | Speculative Loading may increase resource usage, particularly for sites on shared hosting servers.
It is recommended that the plugin be configured based on the available site/server resources to prevent scalability issues. |
PHP Version | The Speculative Loading plugin requires a minimum PHP version of 7.2 or higher. |
WordPress Version | The plugin requires a minimum WordPress version of 6.4, and its functionality has been tested up to version 6.53. |
Plugin Installation | The Speculative Loading plugin has over 10,000+ active installations. |
How to use the Speculation Loading in WordPress?
Speculation rules can be added either in the head or the body of the mainframe.
You can add the Speculation Loading API in two formats:
1. Static setup, you can add a static page URL here. This works well for websites where the next action is very predictable.
2. Dynamic setup is done using JavaScript. This is suitable for websites that heavily use personalized user experiences.
Lets developers and website owners be more specific about which URLs should be prerendered.
Info: You can easily choose between prefetching or prerendering by using inline elements or external text files referenced in the Speculation-Rules (Mozilla) response header.
Method 1: Using Speculative Loading plugin
- Log into your WordPress Dashboard.
- Navigate to the Plugins > Add New Plugin.
- Search for the Speculative Loading plugin.
- Click on Install Now and Activate it.
When you install the plugin, it automatically prerendered linked pages with a moderate eagerness setting. It happens when you hover over a link. So, after activating the plugin, you don’t need to do anything; it works automatically.
If you want, You can change the Speculative Loading section under Settings > Reading.
For example, if you’ve installed the Speculative Loading plugin on a WordPress site, you can use Chrome DevTools to inspect the site.
Click on the Elements tab, and as you scroll down, you’ll see a script type=”speculationrules” that has already been added, containing various speculation rules.
Method 2: Using cPanel
- Log into your cPanel account.
- Navigate to Files > File Manager.
- Inside the public_html directory, select the wp-content folder.
- Open the themes folder, and then select your active theme folder.
- Search for the header.php, right-click on it and choose Edit.
- Add the code (Refer to the code mentioned in Method 3).
Method 3: Using the WordPress dashboard
- Log into your WordPress dashboard.
- Go to the Appearance> Theme File Editor.
- Search for the header.php (Theme Header) file.
- Add the below code, to save changes click on Update File:
Code for static setup
Prerender:
<script type="speculationrules"> { "prerender": [ { "source": "list", "urls": ["shop", "test"] } ] } </script>
Prefetch:
The same goes for prefetching, which is often a good starting point before prerendering:
<script type="speculationrules"> { "prefetch": [ { "urls": ["sample-page", "test1"] } ] } </script>
Code for Dynamic setup
<script type="speculationrules"> { "prerender": [ { "source": "document", "where": { "and": [ { "href_matches": "/*" }, { "not": { "href_matches": [ "/wp-login.php", "/wp-admin/*" ] } } ] }, "eagerness": "moderate" } ] } </script>
In the above code snippet, all URLs on the page are up for prerendering, except for those going to WordPress login and admin pages. You also set how eager it should be.
- Immediate: This guesses as soon as possible when it sees the rules.
- Eager: It works just like the immediate setting. However, in the future, Google plans to make it faster than moderate but not as quick as immediate.
- Moderate: on hover of 200ms
- Conservative: On mouse or touch-down
When you use the Speculation Rules API, you can check it using the Speculative load’s background services in the Chrome Application tab while inspecting the page.
Important Notes:
Immediate and eager settings don’t depend on user actions, so they have higher limits. They can adjust capacity dynamically by removing older pre-rendered pages.
For moderate and conservative settings, you can pre-render up to 2 pages. These are triggered by user actions and follow a First In, First Out (FIFO) rule. If you pre-render a third page, it will replace the first one to save memory.
Eagerness | Prefetch | Prerender |
immediate/eager | 50 | 10 |
moderate/conservative | 2 (FIFO) | 2 (FIFO) |
How do you stop certain URLs from prefetching and prerendering?
It’s worth noting that WP-admin routes are automatically excluded from prerendering and prefetching by default.
You can set the rules for which types of URLs to preload using the plsr_speculation_rules_href_exclude_paths filter speculatively.
The code example below ensures that URLs like https://wordpresssite.com/cart/ or https://wordpresssite.com/cart/checkout/ would be excluded from prefetching and prerendering:
?php add_filter( 'plsr_speculation_rules_href_exclude_paths', function ( $exclude_paths ) { $exclude_paths[] = '/cart/*'; return $exclude_paths; } );
If you see an error saying The Speculation Rules API is disabled, follow the below steps to enable it in your browser settings.
Enable the Speculation Rules API in Chrome
Enabling the Speculation Rules API depends on browser support and specific settings or flags. Currently, not all browsers support this feature by default, and it may still be experimental in some cases.
- Open Chrome, type chrome://flags, and press Enter.
- In the search bar, search Speculation Rules API.
- If the “Speculation Rules API” option appears, set it to Enabled.
- Click the Relaunch button to restart Chrome and apply the changes.
Browser support
The Speculation Rules API is supported in modern Chromium-based browsers like Chrome and Edge, starting from specific versions.
( Source: Mozilla )
You can also check if the browsers support the API with the following code:
if ( HTMLScriptElement.supports && HTMLScriptElement.supports("speculationrules") ) { console.log("Your browser supports the Speculation Rules API."); } OR <script> document.addEventListener('DOMContentLoaded', function() { // Check if the browser supports the Speculation Rules API if ('speculationrules' in document) { console.log("Speculation Rules API is supported."); } else { console.log("Speculation Rules API is not supported."); } }); </script>
Security Consideration
Cross-site prefetching has limits to protect user privacy. It only works if the user doesn’t have cookies set for the destination site, which helps avoid tracking user activity.
Why Use Speculation Rules API On Your Website?
Better page loading times, enhanced user satisfaction and potential SEO benefits make this technology an excellent choice for developers.
By cutting down the delay between page changes, users feel the website is smoother and quicker to respond. You can see this improvement in your site’s Core Web Vitals, where metrics like Largest Contentful Paint (LCP), Cumulative Layout Shift (CLS), and Interaction to Next Paint (INP) drop significantly.
Instant browsing leads to lower bounce rates and higher user retention, which are crucial for your site’s success. This highlights the strategic importance of incorporating the Speculation Rules API.
Speculative Loading vs WP Rocket
The new Speculative Loading is open-source software, and in WordPress, it operates differently from WP Rocket.
WP Rocket is a premium caching plugin that enhances website speed through various optimizations, such as caching, minification, and lazy Loading.
Speculative Loading anticipates user actions to prefetch and prerender content, reducing loading times by preparing the next page a user will visit.
In contrast, WP Rocket offers a link preloading feature that uses JavaScript to preload links when hovered over.
Speculative Loading API allows developers to set rules for the browser to prefetch or prerender linked URLs based on predictions of what users might click next.
Effect of Speculation Rules API on Analytics
Analytics is essential for tracking website usage, including page views and events, and assessing performance through Real User Monitoring (RUM). It’s crucial to understand that prerendering can impact analytics.
For example, If you are using Google Analytics, no additional action is required, as GA handles prerendering by delaying it until activation by default. However, with other analytics tools, prerendered pages might affect data collection.
Site owners may need to add extra code to ensure analytics only activate when the page is viewed. This can be achieved using a Promise that waits for the prerendering change even if a document is being prerendered.
While Google Analytics, Google Publisher Tag (GPT), and Google AdSense delay tracking until a page is active; not all providers do this automatically.
To deal with this, you can set up a Promise to start analytics only when the page is activated:
const whenActivated = new Promise((resolve) => { if (document.prerendering) { document.addEventListener('prerenderingchange', resolve); } else { resolve(); } }); async function initAnalytics() { await whenActivated; // Initialize analytics } initAnalytics();
Conclusion
Speculative Loading can enhance your WordPress site’s page speed by predicting user behaviour and preloading content in the background. This results in faster load times and a smoother, more efficient browsing experience for your visitors.
Frequently Asked Questions
1. Does the Speculative Loading plugin in WordPress utilize AI?
No, the Speculative Loading plugin doesn’t use artificial intelligence (AI). Instead, it uses Google’s Speculation Rules API by inserting a JSON script into any URLs linked on the page and prerendering them with a “moderate” eagerness configuration.
2. Which pages qualify for speculative loading?
Speculative loading strategies can be applied to all pages, but they are not modified by user actions. A good rule of thumb is avoiding prerendering or prefetching checkout and cart pages, which can lead to a poor user experience. Additionally, Google recommends only prerendering pages when there is a high probability (greater than 80%) that users will load them.
The Speculation Rules API enables defining URL patterns to specify which URLs should be eligible for speculative loading.
(Visited 31 times, 31 visits today)
[ad_2]