ForesightJS
website·Indexed 33 days ago
https://foresightjs.comA TypeScript-based library for predictive interaction and prefetching, featuring official integrations for React, Vue, Angular, and Astro. It provides tools like ForesightManager for element registration and prediction strategies for mouse, keyboard, and scroll interactions to improve user experience.
What's inside ForesightJS
- ForesightJS is a lightweight (~32 KB minified) JavaScript library designed to predict user intent and prefetch content before it is needed. It focuses on the 'When' of prefetching—determining the optimal moment to start fetching based on mouse trajectory, tab navigation, and scroll behavior—while the developer provides the 'What' (resource) and 'How' (loading/caching strategy) via a callback. It automatically adapts its strategy based on the device type (mouse, pen, or touch) and respects user data-saver modes or slow connections (default: 3G) by remaining inactive.
Overview of ForesightJS
ForesightJS is a lightweight JavaScript library (~32 KB minified) that predicts user intent to prefetch content before it is needed. It focuses on the 'When' of prefetching by analyzing mouse trajectory, tab navigation, and scroll behavior. Developers provide the 'What' (resource) and 'How' (loading/caching strategy) via a callback when registering an element.Overview of ForesightJS predictive prefetching
ForesightJS is a lightweight JavaScript library (~32 KB minified) that predicts user intent to prefetch content before it is needed. It focuses on the 'When' of prefetching—determining the optimal moment to start fetching based on mouse trajectory, tab navigation, and scroll behavior. Developers provide the 'What' (resource) and 'How' (loading/caching strategy) via a callback when registering elements.Overview of ForesightJS
ForesightJS is a lightweight JavaScript library (~32 KB minified) designed to predict user intent to prefetch content. It focuses on the 'When' of prefetching by analyzing mouse trajectory, tab navigation, and scroll behavior. Users provide the 'What' (resource) and 'How' (loading/caching strategy) via a callback when registering elements. It automatically detects input methods (mouse, pen, touch) and respects user data-saver modes or slow connections (default: 3G) by disabling prefetching.Understand ForesightJS internal architecture
ForesightJS uses a singleton
ForesightManagerto handle prediction logic, global settings, and registered elements (stored in aMap). To avoid performance-heavy reflows while tracking element positions, it employs two primary observers:MutationObserver: Manages elements that are detached or reattached to the DOM, allowing them to be 'parked' and resumed without losing registration.PositionObserver(Shopify library): Asynchronously monitors position changes using a layered approach:VisibilityObserver(viaIntersectionObserver) for viewport visibility,ResizeObserverfor size changes, and target-specificIntersectionObserverinstances withrootMargincalculations for precise observation regions.
Understand ForesightJS architecture and performance
ForesightJS minimizes layout reflows and bundle size through the following mechanisms:
- Position Tracking: Uses Shopify's
PositionObserver(combiningVisibilityObserver,ResizeObserver, andIntersectionObserver) to monitor element positions asynchronously. - Keyboard Prediction: Uses the
tabbablelibrary to determine tab order, caching results to avoid repeatedgetBoundingClientRect()calls. - Bundle Optimization: The library is code-split. Only the Core (~14 KB) is always loaded. Specific handlers (Desktop, Touch) and predictors (Mouse, Tab, Scroll) are lazy-loaded based on the device and enabled settings.
- Position Tracking: Uses Shopify's
Use ForesightElementData for element information
ForesightElementDatais the primary type used to gather information about a registered element. It is returned aselementDatain most ForesightJS events. It contains the element's bounds, registration count, metadata, and detailed callback execution statistics (runtime, status, and error messages).type ForesightElementData = { callback: ForesightCallback name: string id: string elementBounds: { originalRect: DOMRectReadOnly hitSlop: Exclude<HitSlop, number> expandedRect: Readonly<Rect> } trajectoryHitData: TrajectoryHitData isIntersectingWithViewport: boolean element: ForesightElement registerCount: number meta: Record<string, unknown> callbackInfo: { callbackFiredCount: number lastCallbackInvokedAt: number | undefined lastCallbackCompletedAt: number | undefined lastCallbackRuntime: number | undefined lastCallbackStatus: callbackStatus lastCallbackErrorMessage: string | undefined | null reactivateAfter: number isCallbackActive: boolean isRunningCallback: boolean reactivateTimeoutId?: ReturnType<typeof setTimeout> } }Access ForesightJS documentation for LLMs
ForesightJS provides standardizedllms.txtfiles to help Large Language Models understand the library's API and usage patterns. You can access the concise overview viallms.txtor the full context viallms-full.txt. Additionally, any documentation page can be accessed in markdown format by appending.mdto the URL.Main file: https://foresightjs.com/llms.txt Full context: https://foresightjs.com/llms-full.txt Example markdown page: https://foresightjs.com/docs/getting-started/quick-start.mdDebug elements using the DevTools Control Panel
The DevTools Control Panel provides three tabs:
- Settings Tab: Real-time controls for Global Configurations.
- Elements Tab: Overview of registered elements. Statuses are color-coded: Green (Active visible desktop), Grey (Active invisible desktop), Purple (Active touch mode), Yellow (Callback executing), and Light Gray (Inactive).
- Log Tab: Real-time event stream for callback execution and lifecycle events.
Inactive elements display reason badges:
disabled(via settings),detached(removed from DOM),limited(slow network/data saver), orfired(waiting forreactivateAftercooldown).Understand ForesightJS Architecture
ForesightJS utilizes a singleton
ForesightManagerto handle prediction logic and registered elements (stored in aMap). To avoid layout reflows while tracking element positions, it employs:- MutationObserver: Manages elements that are detached or reattached to the DOM.
- PositionObserver (Shopify): Asynchronously monitors position changes using a layered approach:
VisibilityObserver(viaIntersectionObserver) for viewport visibility,ResizeObserverfor size changes, and target-specificIntersectionObserverinstances for precise observation regions.
Compare ForesightJS with traditional prefetching methods
ForesightJS addresses three primary limitations of standard prefetching:
- Hover Latency: Traditional hover-prefetching triggers only after the cursor reaches the element, missing the 100-200ms window of movement toward the target.
- Viewport Waste: Unlike frameworks that prefetch all links entering the viewport (which can cause significant unnecessary data overhead), ForesightJS is more selective.
- Keyboard Exclusion: While hover-based systems ignore keyboard users, ForesightJS explicitly tracks tab navigation to provide performance benefits to keyboard users.
Use ForesightJS llms.txt for AI context
ForesightJS provides standardizedllms.txtfiles to help LLMs understand the library's API and usage patterns. These files provide a concise overview and links to key documentation in markdown format.Main file: https://foresightjs.com/llms.txt Full context: https://foresightjs.com/llms-full.txt