12k
All articles

How to Prefetch Pages Before the User Clicks

Use ForesightJS to prefetch pages before a click using cursor, keyboard and scroll intent. Compare hover prefetching and Speculation Rules, and control network costs.

OpenReplay Team
OpenReplay Team
How to Prefetch Pages Before the User Clicks

To prefetch a page before the user clicks, predict the click from cursor movement, keyboard focus and scroll position, then start loading that page’s data or document in a callback that fires before the pointer reaches the link.

Hover prefetching helps, but the gap between mouseenter and click is often short. When the next route needs a slow API call, the user still sees a spinner.

This guide uses ForesightJS 4.x to fire prefetches earlier, ties them to resource hints like <link rel="prefetch"> or a router’s prefetch method, and compares the approach with plain hover and the Speculation Rules API.

Key Takeaways

  • Intent-based prefetching starts loading a page’s resources when the user’s input suggests a click is coming, without waiting for the click or for the cursor to land on the link.
  • ForesightJS predicts clicks from three desktop signals: mouse trajectory, Tab-key navigation and scroll direction.
  • By default, ForesightJS projects the cursor 120 ms ahead, fires when focus is two tab stops away, and looks 150 px ahead in the scroll direction.
  • ForesightJS never fetches anything itself. It calls your function, so it works for <link rel="prefetch">, router.prefetch(), or a data cache.
  • The Speculation Rules API prefetches or prerenders whole documents from JSON rules, which makes it a poor fit for client-side routers.

What Is Intent-Based Prefetching?

Intent-based prefetching starts loading a page when the user’s input predicts a click, which moves the trigger point earlier than hover. ForesightJS predicts clicks from three desktop signals: the cursor’s projected path, Tab-key focus and scroll direction. Each signal can fire your callback before the pointer touches the link. On desktop that means more time for network work. Fewer prefetches are wasted too, because ForesightJS only registers the links you choose and only fires when input points at them.

To prefetch a link with ForesightJS, install the core package, register each link with ForesightManager.instance.register(), and pass a callback that does the actual prefetch.

pnpm add js.foresight
import { ForesightManager } from "js.foresight"

const prefetched = new Set()

function prefetch(url) {
  if (prefetched.has(url)) return
  prefetched.add(url)
  const link = document.createElement("link")
  link.rel = "prefetch"
  link.href = url
  document.head.append(link)
}

const registrations = [...document.querySelectorAll("a[data-prefetch]")].map(el =>
  ForesightManager.instance.register({
    element: el,
    callback: () => prefetch(el.href),
    hitSlop: 20, // per-element: expand the hit area by 20px on every side
  })
)

// Teardown (e.g. on route change):
// registrations.forEach(r => r.unregister())

The Set makes sure each URL is fetched only once. <link rel="prefetch"> is a resource hint, so the browser is free to ignore it. In v4, register() returns the element’s state together with unregister, subscribe and getSnapshot functions. Elements removed from the DOM are parked rather than unregistered. Change a registered element’s options with updateElementOptions(). The old unregisterOnCallback option is gone, and reactivateAfter (in milliseconds) controls when an element becomes active again.

In a Next.js App Router project, make the callback call router.prefetch(href) from useRouter in next/navigation. The React example below shows how.

Tune How Early Prediction Fires

Four settings decide how early ForesightJS fires: trajectoryPredictionTime, hitSlop, tabOffset and scrollMargin. Set them once with ForesightManager.initialize() at your entry point.

ForesightManager.initialize({
  trajectoryPredictionTime: 120, // default 120 ms; clamped 10–200
  defaultHitSlop: 0,             // default 0; number or per-side rect, up to 2000 per side
  enableTabPrediction: true,
  tabOffset: 2,                  // default 2 tab stops; clamped 0–20
  enableScrollPrediction: true,
  scrollMargin: 150,             // default 150 px; clamped 30–300
})

All of these values are the documented defaults, not recommendations.

SettingDefaultRangeRaise it to…
trajectoryPredictionTime120 ms10–200Fire earlier, with less accuracy
defaultHitSlop / hitSlop00–2000 px per sideMake small targets easier to predict
tabOffset20–20Fire further ahead of keyboard focus
scrollMargin150 px30–300Look further ahead while scrolling

Keep hitSlop small in dense menus. Large hit areas overlap, and then every link the cursor passes counts as a prediction.

Use the React and Vue Packages

ForesightJS 4.0 added official @foresightjs/react and @foresightjs/vue packages. Before v4, the docs gave you premade hooks, composables and directives to copy into your own project. The two packages replace all of that.

pnpm add @foresightjs/react js.foresight
"use client"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { useForesight } from "@foresightjs/react"

export function PrefetchLink({ href, children }: { href: string; children: React.ReactNode }) {
  const router = useRouter()
  const { elementRef } = useForesight<HTMLAnchorElement>({
    callback: () => router.prefetch(href),
    hitSlop: 10,
  })
  return <Link href={href} prefetch={false} ref={elementRef}>{children}</Link>
}

useForesight gives you back an elementRef to attach to the anchor, which is the same pattern used in the official React Router guide. Options like hitSlop and enabled are reactive: change a prop and the registration updates. The package also exports useForesightEvent. For lists, the @foresightjs/react v0.3.0 release added a <Foresight> component that replaces useForesights for registering dynamic lists of elements declaratively.

The Vue package exports a vForesight directive, which takes either a callback or a full options object:

<script setup>
import { vForesight } from "@foresightjs/vue"
const warm = () => fetch("/api/pricing")
</script>

<template>
  <a href="/pricing" v-foresight="warm">Pricing</a>
</template>

How Does ForesightJS Handle Touch Devices?

Touch screens have no cursor, so the ForesightJS touchDeviceStrategy option decides what happens there. The default is onTouchStart, which fires as soon as a finger touches the element. viewport fires when the element scrolls into view. none turns prediction off. Pen input goes through the desktop handler. The ForesightJS homepage dates full touch support to version 3.3.0. Use viewport only for a few high-value links, because it fires for everything the user scrolls past.

Prefetch on Hover vs ForesightJS vs Speculation Rules

Plain hover prefetching is a mouseenter listener. Here is the baseline:

document.querySelectorAll("a[data-prefetch]").forEach(el => {
  const go = () => prefetch(el.href)
  el.addEventListener("mouseenter", go, { once: true })
  el.addEventListener("focus", go, { once: true })
})

The Speculation Rules API works differently. It asks the browser to prefetch or prerender whole documents, based on JSON rules placed in a <script type="speculationrules"> element or served through a Speculation-Rules header. It is supported in Chromium-based browsers such as Chrome and Edge, and other browsers ignore the rules. According to Chrome, speculation rules cover only full-page navigations that the browser itself handles. That makes it a good fit for MPAs and CMS sites (recent WordPress ships it, as the WordPress performance optimization guide describes).

Plain hoverForesightJSSpeculation Rules
TriggerPointer enters linkPredicted trajectory, Tab, scroll, touchBrowser heuristics set by an eagerness setting
What loadsWhatever your handler doesWhatever your callback doesWhole documents
Configured inJSJSJSON
Keyboard/scroll awareFocus onlyYesNo
Fits client-side routingYesYesNo

Control the Cost: Bandwidth and Server Load

Every prediction that doesn’t end in a click costs bandwidth for the user and requests for your server. Three controls keep the cost of intent-based prefetching down.

  1. Gate on connection quality. If you leave minimumConnectionType at its default of 3g, elements stay inactive on slower connections or when data saver is on. The check uses the Network Information API, which isn’t Baseline. It works in Chromium-based browsers but not in Firefox or Safari, so ForesightJS treats the connection as unlimited in those browsers.
  2. Register only likely links. Leave out footer and legal links, and pass enabled: false for links that only sometimes matter.
  3. Prefetch data, not pages. Fetching JSON or a route chunk costs less than fetching full HTML:
const cache = new Map()
const warmProduct = id => {
  if (!cache.has(id)) cache.set(id, fetch(`/api/products/${id}`).then(r => r.json()))
}

Session replays show which links users actually move toward and click, which tells you which links are worth registering in the first place.

Conclusion

Prefetching works best when it starts before the hover. Register only the links that matter, use the callback to warm data or call your router, and keep the default prediction thresholds until real usage shows you need to change them. To start, install js.foresight, swap your mouseenter handler for register(), and leave minimumConnectionType at its default.

FAQs

Why does a page prefetched with link rel='prefetch' download again when the user clicks?

Prefetched responses go into the browser's HTTP cache, so the normal Cache-Control rules decide whether they can be reused. Chromium removed an older five-minute rule that ignored cache headers for prefetched resources. A document served with no-store, or with headers that force revalidation, can trigger a second request on navigation. Give prefetched pages a short max-age, or prefetch data into an in-memory cache instead.

Should I turn off Next.js Link prefetching when using ForesightJS?

Yes, if you want ForesightJS to be the only trigger. In the App Router, Link prefetches a route automatically when it enters the viewport. Setting the prefetch prop to false stops prefetching both on viewport entry and on hover, so router.prefetch runs only when ForesightJS predicts a click. Next.js prefetches only in production builds, so test with next build and next start, not the dev server.

What is the difference between link rel='prefetch' and link rel='preload'?

Preload fetches a resource that the current page needs soon, at high priority, such as a font or a hero image. Prefetch fetches a resource that a future navigation will probably need, at low priority, and the browser may skip it. Use preload for the page that is rendering now. Use prefetch, triggered by hover or ForesightJS, for the page the user is likely to open next.

Understand every bug

Uncover frustrations, understand bugs and fix slowdowns like never before with OpenReplay — self-hosted, with full data ownership.

Star on GitHub

We use cookies to improve your experience. By using our site, you accept cookies.