Small interactions can make a webpage easier to use: opening a tip, changing a setting, or reusing an interface component.
What You Need to Know
Speculation rules can suggest which links a supporting browser should prepare in advance. They are optimization hints, not a promise that navigation will be prefetched or prerendered.
In this example: add a speculation rule for likely navigation.
Try the Example
Take a look at the example. We’ll explain the important lines right below it.
<script type="speculationrules">
{
"prerender": [
{ "source": "list", "urls": ["/next-lesson"] }
]
}
</script>
<a href="/next-lesson">Next lesson</a>
Let’s Read the Code
- <script>: Script contains JavaScript, data, or other browser-understood script formats depending on type.
- type: Type changes what sort of control or resource the browser uses.
- href: Href is the URL to a related resource or destination.
Read the named elements and attributes together. They explain how the browser connects this feature to the rest of the page.
What Happens in the Browser?
When this example includes JavaScript, it supplies behavior that ordinary HTML does not automatically provide. Always think about a fallback.
Start with native behavior. Details, dialog, and popover each solve a different interface problem. Choose the simplest control that actually matches what a visitor wants to do, then test focus and dismissal as well as appearance.
Your Turn
Run this on a local development server if it loads modules or resources. Change the visible text or trigger and check what still works with scripts disabled.
Common Beginner Mistakes
- Expecting the page to run scripted behavior when the required JavaScript is missing.
- HTML supplies structure; JavaScript is necessary for the scripted behavior in this example. Check keyboard access and focus movement too.
Key Takeaways
- Speculation rules can suggest which links a supporting browser should prepare in advance.
- <script>: Script contains JavaScript, data, or other browser-understood script formats depending on type.
- Test the behavior you expect rather than trusting how the snippet looks in your editor.