ForesightJS

website·Indexed 33 days ago

https://foresightjs.com

A 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.

Tokens
58.3K
Snippets
276
Records
355
Agent score
62%

What's inside ForesightJS

  1. Overview of 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.
  2. 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.
  3. 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.
  4. 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.
  5. Understand ForesightJS internal architecture

    ForesightJS uses a singleton ForesightManager to handle prediction logic, global settings, and registered elements (stored in a Map). To avoid performance-heavy reflows while tracking element positions, it employs two primary observers:

    1. MutationObserver: Manages elements that are detached or reattached to the DOM, allowing them to be 'parked' and resumed without losing registration.
    2. PositionObserver (Shopify library): Asynchronously monitors position changes using a layered approach: VisibilityObserver (via IntersectionObserver) for viewport visibility, ResizeObserver for size changes, and target-specific IntersectionObserver instances with rootMargin calculations for precise observation regions.
  6. Understand ForesightJS architecture and performance

    ForesightJS minimizes layout reflows and bundle size through the following mechanisms:

    • Position Tracking: Uses Shopify's PositionObserver (combining VisibilityObserver, ResizeObserver, and IntersectionObserver) to monitor element positions asynchronously.
    • Keyboard Prediction: Uses the tabbable library to determine tab order, caching results to avoid repeated getBoundingClientRect() 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.
  7. Use ForesightElementData for element information

    ForesightElementData is the primary type used to gather information about a registered element. It is returned as elementData in 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>
      }
    }
  8. Access ForesightJS documentation for LLMs

    ForesightJS provides standardized llms.txt files to help Large Language Models understand the library's API and usage patterns. You can access the concise overview via llms.txt or the full context via llms-full.txt. Additionally, any documentation page can be accessed in markdown format by appending .md to 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.md
  9. Debug 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), or fired (waiting for reactivateAfter cooldown).

  10. Understand ForesightJS Architecture

    ForesightJS utilizes a singleton ForesightManager to handle prediction logic and registered elements (stored in a Map). 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 (via IntersectionObserver) for viewport visibility, ResizeObserver for size changes, and target-specific IntersectionObserver instances for precise observation regions.
  11. Compare ForesightJS with traditional prefetching methods

    ForesightJS addresses three primary limitations of standard prefetching:

    1. Hover Latency: Traditional hover-prefetching triggers only after the cursor reaches the element, missing the 100-200ms window of movement toward the target.
    2. Viewport Waste: Unlike frameworks that prefetch all links entering the viewport (which can cause significant unnecessary data overhead), ForesightJS is more selective.
    3. Keyboard Exclusion: While hover-based systems ignore keyboard users, ForesightJS explicitly tracks tab navigation to provide performance benefits to keyboard users.
  12. Use ForesightJS llms.txt for AI context

    ForesightJS provides standardized llms.txt files 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