ForesightJS Documentation

repository·main·Indexed 23 days ago

https://github.com/spaansba/foresightjs

A lightweight, framework-agnostic library that predicts user intent to prefetch content and reduce perceived latency. Includes specialized integrations for React, Vue, Angular, and Astro, as well as dedicated development tools via js.foresight-devtools for debugging trajectories and hit-slop boundaries.

Tokens
61.9K
Snippets
156
Records
313
Agent score
75%

What's inside ForesightJS

  1. What is ForesightJS and how does it work?

    main

    ForesightJS is a lightweight JavaScript library designed to predict user intent, allowing you to prefetch content before a user explicitly requests it.

    It solves the problem of when to fetch data by analyzing user behavior such as mouse trajectory and tab navigation. This allows for proactive loading that works out of the box for both desktop and mobile devices.

    To use ForesightJS, you follow a simple mental model:

    1. ForesightJS handles the 'When': It predicts the optimal moment to start fetching based on intent.
    2. You handle the 'What' and 'How': You provide a callback function when registering an element that defines which resource to load and which loading/caching strategy to use.
  2. What is ForesightJS?

    main

    ForesightJS is a lightweight JavaScript library with full TypeScript support designed to predict user intent. It achieves this by analyzing user interactions such as mouse movements and keyboard navigation to enable proactive optimizations like:

    • Mouse prediction: Anticipating where a user is moving their cursor.
    • Tab prediction: Predicting which tab or navigation element a user might select.
    • Mobile/Desktop prefetching: Triggering resource prefetching based on predicted intent to improve perceived performance.
  3. What is ForesightJS in Vue

    main

    ForesightJS is a lightweight library designed to predict user intent based on mouse movements and keyboard navigation (such as tab prediction).

    When using ForesightJS within a Vue application, you interact with it via the official @foresightjs/vue package using two primary mechanisms:

    1. The v-foresight directive: Used to register specific DOM elements for tracking and prediction.
    2. Composables: Used to access and react to the prediction state within your component logic.
  4. Overview of ForesightJS

    main
    ForesightJS is a lightweight JavaScript library designed to predict user intent and prefetch content before it is explicitly requested. This improves perceived application speed by initiating data or asset loading based on user behavior. It is framework-agnostic and works out of the box without mandatory configuration, automatically adapting its prediction strategies based on whether the user is on a desktop/keyboard device or a mobile/touch device.
  5. Available @foresightjs/angular features

    main

    The Angular package provides several ways to integrate ForesightJS:

    • ForesightDirective: A standalone [fsForesight] directive for element registration via callback or options object.
    • ForesightService: An injectable service for manual registration and subscribing to manager events.
    • ForesightComponent: A standalone wrapper component that registers its host element.
    • injectForesightEvent: A helper function to subscribe to a ForesightManager event for the lifetime of the current injection context.
  6. How ForesightJS and Astro prefetch compose

    main

    ForesightJS acts as a fifth prefetch strategy that works alongside Astro's native four strategies.

    A link is handled by ForesightJS if:

    1. It has an explicit data-astro-prefetch="foresight" attribute.
    2. It has no data-astro-prefetch attribute, AND you have configured prefetchAll: true with defaultStrategy: "foresight" in your integration settings.

    Note: Only same-origin links are registered.

    Behavior and Fallbacks

    • Astro Compatibility: When a ForesightJS callback fires, the page is fetched via Astro's own prefetch() from astro:prefetch. This ensures that slow-connection detection, deduplication, and Speculation Rules upgrades are maintained.
    • Graceful Fallback: On slow connections or in data-saver mode, ForesightJS links automatically fall back to Astro's tap strategy.
    • Dynamic Links: Links are automatically re-scanned after view transitions or when anchors are injected/removed (e.g., via Server Islands).
  7. When to use v-foresight vs useForesight

    main

    The v-foresight directive is designed for the simplest prefetching implementation: you attach it to an element, provide a callback, and the directive handles registration and unregistration automatically.

    If you need access to the element's actual prediction state (e.g., to change UI based on how likely a user is to interact with an element), you should use the useForesight composable instead.

  8. How mouse prediction works

    main

    Mouse prediction anticipates click targets by analyzing cursor velocity and trajectory.

    Mechanism:

    1. Tracking: mousemove events record clientX and clientY coordinates. The amount of history kept is controlled by the positionHistorySize setting.
    2. Algorithm: The predictNextMousePosition function uses linear extrapolation. It calculates average velocity from the position history and projects the current position along the trajectory based on the trajectoryPredictionTimeInMs setting.
    3. Intersection: The library uses the Liang-Barsky line clipping algorithm (lineSegmentIntersectsRect) to check if the predicted path intersects an element's rectangle. This check includes the element's hitSlop to increase accuracy.
  9. Configure Prediction Strategies in ForesightManager

    main

    ForesightJS uses different prediction strategies based on the device type. You can customize which strategies are active when initializing the ForesightManager.

    Keyboard/Mouse Users

    By default, all strategies are enabled. You can disable specific ones during initialization:

    • Mouse Trajectory (default): Analyzes cursor movement patterns to predict and prefetch content before the user arrives at a link.
    • Keyboard Navigation (default): Tracks tab key usage to prefetch when a user is $N$ tab stops away from a registered element.
    • Scroll (default): Prefetches content when users scroll towards registered elements based on scroll direction.

    Touch Devices

    Touch devices use a single active strategy. You can configure this during ForesightManager initialization:

    • onTouchStart (default): Captures the initial touch event to begin prefetching.
    • Viewport Enter: Detects when registered elements enter the viewport and prefetches based on visibility.
    • None: Disables ForesightJS on touch devices.
  10. How ForesightJS prediction strategies work

    main

    ForesightJS automatically switches prediction logic based on the detected device type to ensure optimal performance and accuracy:

    Desktop/Keyboard Users

    Uses behavior-based tracking including:

    • Mouse trajectory prediction: Anticipating where the user is moving the cursor.
    • Keyboard navigation tracking: Monitoring focus and navigation patterns.
    • Scroll-based prefetching: Predicting content needs based on scroll velocity and direction.

    Mobile Devices

    Uses touch-based signals including:

    • Viewport enter detection: Predicting intent when elements enter the viewport.
    • Touch start events: Using initial touch contact to anticipate navigation (this behavior is configurable via the touchDeviceStrategy option).
  11. Understand the DevTools Control Panel tabs

    main

    The ForesightDevtools control panel provides three distinct views for debugging:

    Settings Tab

    Provides real-time controls for all Global Configurations. Changes made here immediately affect the ForesightManager configuration, allowing you to test different settings without code changes.

    Elements Tab

    Displays all elements currently registered with ForesightManager, categorized into Active and Inactive sections.

    Status Indicators:

    • 🟢 Green: Active visible elements (desktop mode).
    • Grey: Active invisible elements (desktop mode).
    • 🟣 Purple: Active elements in touch device mode (visibility is not tracked in this mode).
    • 🟡 Yellow: Elements whose callbacks are currently executing.
    • 🔘 Light Gray: Inactive elements.

    Inactive Reason Badges:

    • disabled: Turned off via the enabled option.
    • parked: Removed from the DOM (isParked: true); the element remains registered but inactive.
    • limited: On a limited connection (data saver/slow network).
    • fired: Callback has already run and is waiting on reactivateAfter.

    Log Tab

    Displays real-time events emitted by ForesightJS, such as callback execution times and lifecycle events. You can also print the complete ForesightManager.instance.getManagerData state directly from this tab.

    Note: Avoid logging frequently emitted events to the browser console to prevent performance degradation; use the controlPanel instead.

  12. Understand ForesightJS bundle optimization

    main

    ForesightJS is designed for efficient code splitting. While the full library is ~32 KB minified, the library lazy-loads handlers and predictors based on the device type and enabled features. This ensures users only download the code they actually use.

    ChunkSizeLoaded When
    Core~14 KBAlways (initial load)
    DesktopHandler + MousePredictor~15 KBDesktop/mouse users
    TouchDeviceHandler~2 KBTouch device users
    TabPredictor + tabbable~7 KBenableTabPrediction: true
    ScrollPredictor~1.5 KBenableScrollPrediction: true
    Touch predictors~1.5 KBTouch device (based on strategy)

    Example Scenarios:

    • Touch Device: Loads Core + TouchDeviceHandler + one Touch predictor.
    • Desktop User: Loads Core + DesktopHandler + enabled predictors (Mouse, Tab, or Scroll).