Created
April 15, 2024 10:58
-
-
Save worldoptimizer/495a02a6697331165c7806dcce1245c2 to your computer and use it in GitHub Desktop.
Speculation Rules API (WordPress Plugin)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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