Skip to content

Instantly share code, notes, and snippets.

@worldoptimizer
Created April 15, 2024 10:58
Show Gist options
  • Save worldoptimizer/495a02a6697331165c7806dcce1245c2 to your computer and use it in GitHub Desktop.
Save worldoptimizer/495a02a6697331165c7806dcce1245c2 to your computer and use it in GitHub Desktop.
Speculation Rules API (WordPress Plugin)
<?php
/**
* Plugin Name: Speculation Rules Prefetch
* Description: A WordPress plugin to prefetch links using Speculation Rules API
* Version: 1.0
* Author: Max Ziebell
*/
// 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>
// Feature detect Speculation Rules API support
if (HTMLScriptElement.supports && HTMLScriptElement.supports('speculationrules')) {
// Get all anchor tags in the document
const anchors = Array.from(document.querySelectorAll('a'));
// Filter out external links
const sameDomainLinks = anchors
.map(a => a.href)
.filter(href => new URL(href).origin === window.location.origin);
// Create speculation rules script element
const specScript = document.createElement('script');
specScript.type = 'speculationrules';
const specRules = {
prefetch: [
{
source: 'list',
urls: sameDomainLinks,
},
],
};
specScript.textContent = JSON.stringify(specRules);
console.log('Added speculation rules for prefetching');
document.body.appendChild(specScript);
} else {
console.log('Your browser does not support the Speculation Rules API.');
}
</script>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment