Hey WordPress Devs, Check Out My Latest Experiment—Speculation Rules Prefetch!
Hey folks! ![]()
So, I’ve been messing around with this new thing called the Speculation Rules API, and I whipped up a WordPress plugin that’s all about making your site faster. It’s called Speculation Rules Prefetch, and I’d love for you all to test it out!
Based on:
What’s the idea?
Okay, so here’s the gist. The plugin scans all the links on your page and uses the Speculation Rules API to tell your browser, “Hey, these are the links that are probably gonna be clicked on, so let’s load 'em up faster!”
The Nitty-Gritty 
We’re talking about:
- Prefetching links that are from the same domain.
- Prioritizing based on where they show up on the screen and how big they are.
- Oh, and we’re smart about it—we only grab the first 5 links for each top-level path, so it’s not like we’re downloading the entire internet or anything.
- To view a console dump of the added links, simply append
?debugto the URL. Alternatively, you can inspect the source code directly.
Why Should You Care?
Speculation Rules API is the new cool kid on the block for browser speed. It’s like giving the browser a cheat sheet for what the user will likely do next. Faster loading times = happier users. Simple as that.
<?php
/**
* Plugin Name: Speculation Rules Prefetch
* Description: A WordPress plugin to prefetch links using Speculation Rules API
* Version: 1.0
* Author: Max Ziebell
* License: MIT
*/
/*
MIT License
Copyright (c) 2023 Max Ziebell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// Hook for adding speculation rules to the WordPress footer
add_action('wp_footer', 'add_speculation_rules');
// Action function for the above hook
function add_speculation_rules() {
?>
<script>
// Configuration
const maxLinksPerPath = 5;
const debugMode = new URLSearchParams(window.location.search).has('debug');
// Helper function to get element properties
const getElementProperties = (href) => {
const elem = document.querySelector(`a[href="${href}"]`);
if (!elem) return null;
const rect = elem.getBoundingClientRect();
const size = rect.width * rect.height;
return { y: rect.y, size };
};
// Main function to sort links by position and size
const sortLinksByPositionAndSize = (links) => {
const linkProperties = links.map((link) => ({
link,
properties: getElementProperties(link),
}));
return linkProperties
.filter(({ properties }) => properties !== null)
.sort((a, b) => {
if (a.properties.y !== b.properties.y) {
return a.properties.y - b.properties.y;
}
return b.properties.size - a.properties.size;
})
.map(({ link }) => link);
};
// Feature detect Speculation Rules API support
if (HTMLScriptElement.supports && HTMLScriptElement.supports('speculationrules')) {
const links = document.querySelectorAll('a');
const anchors = Array.from(links);
const filteredLinks = anchors
.map(a => a.href)
.filter(href => new URL(href).origin === window.location.origin);
const uniqueLinks = [...new Set(filteredLinks)];
// Apply sorting
const sortedLinks = sortLinksByPositionAndSize(uniqueLinks);
// Create speculation rules script element
const specScript = document.createElement('script');
specScript.type = 'speculationrules';
const specRules = {
prefetch: [
{
source: 'list',
urls: sortedLinks,
},
],
};
specScript.textContent = JSON.stringify(specRules);
document.body.appendChild(specScript);
if (debugMode) {
console.log('Added speculation rules for prefetching', sortedLinks);
}
} else if (debugMode) {
console.log('Your browser does not support the Speculation Rules API.');
}
</script>
<?php
}
Drop your thoughts right here in this thread and let me know if it works for you.