Skip to main content
Version: 4.x

Behind the Scenes

note

Reading this is not necessary to use the library; this is just for understanding how ForesightJS works.

Architecture​

ForesightJS uses a singleton pattern with ForesightManager as the central instance managing all prediction logic, registered elements, and global settings. Elements are stored in a Map where the key is the registered element itself. Registering the same element again patches its options, preserving its identity, state, and subscriptions. Omitted options keep their current values.

Since DOM elements can change position and we need to keep the DOM clean, we require element.getBoundingClientRect() for each element on each update. To avoid triggering reflows, ForesightJS uses observers:

  • MutationObserver: Detects when registered elements are detached from or reattached to the DOM, so they can be parked (kept registered but inactive) and resumed. This keeps prediction working across detach/reattach and re-parenting
  • PositionObserver: Shopify's library that asynchronously monitors element position changes without polling

The PositionObserver uses layered observation:

  1. VisibilityObserver (built on IntersectionObserver) determines if elements are viewport-visible
  2. ResizeObserver tracks size changes of visible target elements
  3. Target-specific IntersectionObserver instances with smart rootMargin calculations transform viewport observation into target-specific observation regions

Keyboard & Mouse Users​

Mouse Prediction​

Mouse prediction tracks cursor movement patterns to anticipate click targets by analyzing velocity and trajectory.

Event Handling: pointermove events record clientX, clientY and the event timestamp for mouse and pen input.

Prediction Algorithm: The predictNextMousePosition function implements damped extrapolation:

  1. History Tracking: Stores past mouse positions with timestamps
  2. Velocity Calculation: Fits a least-squares velocity through the positions of the last 80ms. Older positions are ignored, so the result does not depend on the display refresh rate and a movement that starts after a pause is picked up immediately
  3. Extrapolation: Projects current position along trajectory using calculated velocity and trajectoryPredictionTime setting. Real cursors brake harder the faster they move, so the reach grows with the logarithm of the speed instead of linearly. This keeps fast flicks from overshooting past the element the user is heading for

Intersection Detection: The lineSegmentIntersectsRect function implements the Liang-Barsky line clipping algorithm to check intersections between the predicted mouse path and element rectangles:

  1. Line segment defined by current and predicted mouse positions
  2. Target rectangle includes element's hitSlop
  3. Algorithm clips line segment against rectangle's four edges
  4. Intersection confirmed if entry parameter ≤ exit parameter

Keyboard Prediction​

Tab prediction monitors keyboard navigation by detecting Tab key presses and focus changes.

Event Handling:

  • keydown: Detects Tab key presses
  • focusin: Fires when elements gain focus

When focusin follows a Tab keydown, ForesightJS identifies this as tab navigation.

Tab Navigation Logic: Uses the tabbable library to determine tab order. Results are cached for performance since tabbable() calls getBoundingClientRect() internally. Cache invalidates on DOM mutations.

Prediction process:

  1. Identify current focused element's index in tabbable elements list
  2. Determine tab direction (forward/backward based on Shift key)
  3. Calculate prediction range using current index, direction, and tabOffset
  4. Trigger callbacks for registered elements within predicted range

Scroll Prediction​

Leverages existing observer infrastructure without additional event listeners. The PositionObserver callback provides elements that have moved. By analyzing the delta between previous and new boundingClientRect for viewport-remaining elements, ForesightJS infers scroll direction.

Note: This also triggers during animations or dynamic layout changes.

Touch Device Users​

Touch devices have no continuous cursor, so prediction works differently. The touchDeviceStrategy setting picks one of two active strategies (a third, "none", turns touch prediction off entirely):

Viewport Entry: Uses IntersectionObserver to detect when elements enter the viewport. Callbacks trigger when elements become visible during scrolling, providing anticipatory loading for content that will soon be in view.

Touch Start: Listens for pointerdown events on registered HTML elements. Callbacks fire when users begin interacting with an element, before the actual click event occurs, providing a performance advantage for touch interactions.

Element Lifecycle​

  1. Registration: ForesightManager.instance.register({ element, callback }) adds the element to the internal Map
  2. Callback Execution: When user intent is detected, element's callback function triggers
  3. Deactivation: isPredicted set to true and the element becomes inactive after callback execution
  4. Reactivation Wait: Element remains inactive for reactivateAfter duration (defaults to infinity)
  5. Reactivation: Element becomes active again after duration elapses

Cleanup: Elements are removed via ForesightManager.instance.unregister(element). Detaching an element from the DOM does not unregister it. The MutationObserver parks it (keeps it registered but inactive) and resumes it when it reattaches.

Bundle Optimization​

The full library is ~39 KB minified (~13 KB gzipped) including its dependencies, but you never load all of it. Code splitting lazy-loads the handler for the current device type and the tab predictor:

ChunkSizeContainsLoaded When
Core~17 KBForesightManagerAlways (initial load)
DesktopHandler~12 KBMouse and scroll predictors, position-observerDesktop/mouse users
TabPredictor + tabbable~7 KBTab predictorenableTabPrediction: true
TouchDeviceHandler~2 KBViewport and touch start predictorsTouch device users

Result: a touch device loads the core and the touch handler. A desktop user loads the core, the desktop handler and, when tab prediction is enabled, the tab predictor.