Subtlyv0.1.1
Menus & navigation

intentPrefetch()

Load a link when someone is likely to open it. Safe navigation links.

Available in v0.1.1prefetch.jsPerformance

Try it

Hover or focus this documentation link for 120 ms. A same-origin prefetch hint is added. Your browser may skip the actual request when data saving or network conditions call for it.

Live example
Prefetch hint Not addedIntent delay 120 ms

Hover or focus the link.

<div id="your-component">
<nav class="prefetch-preview" aria-label="Prefetch demonstration"><span class="sample-label">Read next</span><a href="guide-vanilla.html" data-prefetch><strong>Use Subtly with vanilla JavaScript</strong><span>Learn how to initialize and clean up a component.</span></a></nav><div class="demo-metrics"><span>Prefetch hint <strong data-hint>Not added</strong></span><span>Intent delay <strong>120 ms</strong></span></div><p class="demo-status" role="status">Hover or focus the link.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const link = el.querySelector('a');
          const observer = new MutationObserver(() => {
            const added = [...document.head.querySelectorAll('link[rel="prefetch"]')]
              .some(hint => hint.href === link.href);
            if (added) {
              el.querySelector('[data-hint]').textContent = 'Added';
              status('Same-origin hint added. The browser decides whether to fetch.');
            }
          });
          observer.observe(document.head, { childList: true });
          const stop = kit.intentPrefetch(el.querySelector('nav'), { delay: 120 });
          return () => { stop(); observer.disconnect(); };
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Add it to your project

  1. Copy the HTML. Use the HTML tab above and place the markup inside a dedicated component root. Layout classes belong to this documentation website; use your own styles.
  2. Connect the behavior. Copy the JavaScript tab, update #your-component and initialize it after the elements exist. Replace simulated operations with your own data.
  3. Clean up on unmount. Call the example’s cleanup() when the component is removed. It aborts application listeners and releases the utility’s timers or observers.

The preview and JavaScript tab use the same utility wiring. status() writes plain text into the example’s status element. wait() is a simulated local delay. For examples with data-ix attributes, start the declarative runtime once at application level, as shown in the code. Use your framework guide to place setup and cleanup correctly.

API and lifecycle

Attach the helper to a root containing explicitly opted-in links. After mouse hover or keyboard focus, it adds same-origin document prefetch hints. Defaults: 120 ms delay, 12 unique URLs per instance.

Interface
selector, delay=120, max=12; returns cleanup.
Lifecycle
The returned cleanup cancels the timer, removes listeners and removes the hints it created. Browsers may ignore prefetch hints; they do not guarantee a fetch or faster navigation.

Accessibility and safety

Implementation notes

Opt in only for safe same-origin GET pages. Do not prefetch logout, checkout or token links.

Opt in only safe, cacheable GET pages. Exclude logout, checkout, action links and private token URLs. The helper also checks connection-saving signals.

What to check

Hover or focus an eligible link and inspect for a prefetch hint. Verify excluded links, cross-origin pages and download links are not prefetched.

View documented module source
/** Intent-based same-origin document prefetch. Opt in only safe, cacheable GET URLs.
 * Browser may ignore the hint. Never use for checkout, logout or private token links. */
export function intentPrefetch(root,{selector='a[data-prefetch]',delay=120,max=12}={}){
    const seen=new Set(), links=new Set();let timer;
    function cancel(){clearTimeout(timer);}
    function start(e){const a=e.target.closest?.(selector);if(!a||!root.contains(a)||a.hasAttribute('download')||e.pointerType&&e.pointerType!=='mouse')return;cancel();const url=new URL(a.href,location.href);url.hash='';if(url.origin!==location.origin||url.protocol!==location.protocol||seen.has(url.href)||seen.size>=max||navigator.connection?.saveData||/^(slow-)?2g$/.test(navigator.connection?.effectiveType||''))return;
        timer=setTimeout(()=>{const link=document.createElement('link');link.rel='prefetch';link.href=url.href;seen.add(url.href);links.add(link);document.head.append(link);},delay);}
    root.addEventListener('pointerover',start);root.addEventListener('pointerout',cancel);root.addEventListener('focusin',start);root.addEventListener('focusout',cancel);
    return ()=>{cancel();root.removeEventListener('pointerover',start);root.removeEventListener('pointerout',cancel);root.removeEventListener('focusin',start);root.removeEventListener('focusout',cancel);for(const link of links)link.remove();};
}

Search Subtly documentation

Popular pages
↑↓ to navigate↵ to openESC to close