Quick Start
Register your first element with ForesightJS and see how prediction works.
Basic Usage Example
This example is vanilla JS. Most people use ForesightJS with a framework, covered below.
import { ForesightManager } from "js.foresight"
const myButton = document.querySelector("#my-button")
ForesightManager.instance.register({
element: myButton,
callback: () => console.log("prefetch logic here"),
})
That's it!
If you permanently remove a registered element from the DOM, call ForesightManager.instance.unregister(element) to stop tracking it. Detaching an element does not unregister it. It is parked (kept registered but inactive) and resumes if it reattaches, so an element you discard without unregistering stays parked and cannot be garbage collected. The official React, Vue, and Angular integrations do this for you on unmount, and the Astro integration unregisters links that leave the DOM.
Provide registration options
For finer control, pass any of these options:
import { ForesightManager } from "js.foresight"
const myButton = document.querySelector("#my-button")
ForesightManager.instance.register({
element: myButton,
callback: () => console.log("prefetch logic here"),
hitSlop: 50, // slop around the element, making its hitbox bigger
name: "My Foresight button!", // name visible in the debug tools
meta: {
route: "/about",
}, // your custom meta data for analytics
reactivateAfter: 5 * 60 * 1000, // time for the element to reactivate after the callback has been hit
})
Using a framework?
ForesightJS is framework agnostic, but official React, Vue, Angular, and Astro packages exist that handle registration for you. Switch framework with the dropdown at the top of the sidebar to read those docs. Using something else? See Other Frameworks for how to build your own binding.
Development Tools
ForesightJS has dedicated Development Tools that help you understand and tune how prediction is working in your application:
pnpm add js.foresight-devtools
# or
npm install js.foresight-devtools
# or
yarn add js.foresight-devtools
import { ForesightDevtools } from "js.foresight-devtools"
// Initialize development tools
ForesightDevtools.initialize({
// optional props
})