Prefetch System
The Prefetch system makes the application feel instant by pre-loading pages when a user hovers over a link, before they even click.
Table of Contents
1. How It Works
Goal: Understand how to make your app feel instant by pre-loading pages before the user even clicks.
The system uses a smart hover strategy to predict intent:
- Hover Detect: When a user mouse-overs a link, a timer starts.
- Intent Delay: If the mouse stays for 65ms, we assume intent to click.
- Fetch: A
fetch()request is sent in the background withX-Prefetch: true. - Cache: The HTML response is parsed and stored in an in-memory Map (max 5 mins).
- Click: If the user clicks, we swap the
bodycontent instantly from cache instead of doing a full page reload.
Note: If the user clicks before the prefetch is done, it waits for the ongoing request and then swaps content, which is still faster than a fresh navigation.
2. Installation
Task: Add the prefetch script to your main layout file (`public.php`) to enable it globally.
3. Usage & Configuration
Smart Defaults
By default, prefetch is enabled for all internal links on the same domain.
It automatically skips:
- External links
- Download links (.pdf, .zip, etc.)
- Current page links
- Anchor links (#fragment)
Control via Attributes
You can control prefetch behavior using data-prefetch attributes in your HTML:
LogoutHeavy PageGlobal Configuration
You can configure the system by setting window.PrefetchConfigbefore the scripts load:
3. JavaScript API
The system exposes a global window.Prefetch object:
// Manually prefetch a URL
Prefetch.prefetch('/admin/dashboard').then(cacheEntry => {
console.log('Page loaded!', cacheEntry);
});
// Programmatic navigation (uses cache if available)
Prefetch.navigateTo('/admin/dashboard');
// Clear cache (useful after form submissions)
Prefetch.clearCache();Events
Listen for events to re-initialize your own JavaScript components after a page swap:
window.addEventListener('prefetch:navigate', (e) => {
console.log('Navigating to:', e.detail.url);
});
window.addEventListener('prefetch:loaded', () => {
console.log('New content loaded!');
// Re-initialize tooltips, graphs, etc.
MyPlugin.init();
});