What Is the intersectionObserver Module in Web-Tracing? Element Exposure Tracking Explained

The intersectionObserver module is the core visibility tracking component that monitors when DOM elements enter or leave the viewport and emits detailed exposure events with precise timing data.

The intersectionObserver module in the web-tracing SDK provides a framework-agnostic solution for tracking element exposure metrics. Located in the core package at packages/core/src/lib/intersectionObserver.ts, this module leverages the native Intersection Observer API to capture precise visibility timestamps and user-defined parameters. It enables detailed analytics on how users interact with specific page elements across Vue 2, Vue 3, and React applications.

Core Functionality of the intersectionObserver Module

The module serves as the SDK's engine for recording element visibility events, implementing several specialized responsibilities to ensure accurate tracking.

Threshold-Based Observer Management

The module creates separate IntersectionObserver instances for each configured visibility threshold. This architectural decision prevents the same DOM node from being observed by multiple observers simultaneously, which could cause conflicting callbacks. The Intersection class defined in packages/core/src/lib/intersectionObserver.ts manages these instances, mapping each threshold value to its own dedicated observer to ensure clean separation of concerns.

Exposure Timing Capture

When a tracked element becomes visible (isIntersecting returns true), the module immediately records the showTime timestamp. Upon the element leaving the viewport, it captures showEndTime and triggers event emission through sendData.emit. This millisecond-precision timing allows analytics systems to calculate exact exposure duration, distinguishing between brief scroll-past views and meaningful engagement.

Custom Data Aggregation

The module accepts a params object from developers, attaching this custom metadata directly to the event payload. This extensibility allows teams to correlate exposure events with specific business context—such as campaign identifiers, A/B test variants, or element categories—without modifying the core SDK code.

Source Code Architecture and File Locations

The implementation spans several key files within the m-cheng-web/web-tracing repository, each serving distinct architectural purposes:

Implementing Element Exposure Tracking

The module exposes a consistent API across all supported frameworks, enabling developers to track element visibility with minimal configuration.

Basic Usage Across Frameworks

Import the tracking functions from your specific framework package and invoke intersectionObserver() with a target element and configuration options:

import {
  intersectionObserver,
  intersectionUnobserve,
  intersectionDisconnect
} from '@web-tracing/vue3'  // or @web-tracing/vue2, @web-tracing/react

const target = document.querySelector('#hero-banner');

// Start tracking visibility when 50% of element is visible
intersectionObserver({
  target,
  threshold: 0.5,
  params: { campaignId: 'summer-sale', elementType: 'banner' }
});

// Stop tracking specific element
intersectionUnobserve(target);

// Cleanup all observers on component unmount or page unload
intersectionDisconnect();

These framework wrappers implement thin proxies to the core SDK methods:

// Framework wrapper implementation pattern
export function intersectionObserver(gather) {
  _support.intersection?.observe(gather)
}
export function intersectionUnobserve(target) {
  _support.intersection?.unobserve(target)
}
export function intersectionDisconnect() {
  _support.intersection?.disconnect()
}

Event Payload Structure

When visibility changes occur, the module emits a structured data object containing temporal and contextual information:

{
  "eventType": "intersection",
  "threshold": 0.5,
  "observeTime": 1689734412090,
  "showTime": 1689734412098,
  "showEndTime": 1689734414097,
  "params": { "campaignId": "summer-sale", "elementType": "banner" },
  "triggerPageUrl": "http://localhost:6656/#/intersection"
}

The observeTime marks when tracking began, showTime records when the element entered the viewport, and showEndTime captures when it exited. This schema enables downstream analytics to calculate total exposure duration and correlate visibility with conversion events.

Summary

  • The intersectionObserver module provides the core functionality for tracking DOM element visibility using the native Intersection Observer API.
  • It creates dedicated observer instances per threshold to prevent observation conflicts and ensure accurate, independent timing data for each visibility ratio.
  • The module captures millisecond-precision timestamps (showTime, showEndTime) and emits structured events through sendData.emit when elements enter and leave the viewport.
  • Framework-agnostic wrapper functions—intersectionObserver, intersectionUnobserve, and intersectionDisconnect—are exposed through Vue 2, Vue 3, and React packages for consistent developer experience.
  • Lifecycle management is handled through initIntersection() during SDK startup and destroyIntersection() during teardown, as implemented in packages/core/index.ts, preventing memory leaks in single-page applications.

Frequently Asked Questions

What does the intersectionObserver module track?

The module tracks element exposure events, recording precisely when DOM elements enter and leave the viewport based on configured visibility thresholds. It captures timestamps for observation initialization (observeTime), visibility start (showTime), and visibility end (showEndTime), along with arbitrary user-defined parameters and the threshold value that triggered the event.

How do I stop observing a specific element?

Call the intersectionUnobserve(target) function with the DOM element as the sole argument. This removes the specific target from the internal observation list without affecting other tracked elements on the page. To completely terminate all active observations and free resources, invoke intersectionDisconnect(), which is typically called during component unmounting or page navigation.

Where is the observer initialized in the SDK lifecycle?

The observer initializes automatically during SDK startup within packages/core/index.ts, specifically at lines 38-41 where initIntersection() is invoked as part of the main initialization sequence. The module also registers destroyIntersection() for cleanup when the SDK instance is destroyed, ensuring proper resource disposal and preventing memory leaks in long-running single-page applications.

What data is included in the intersection event payload?

The emitted event payload contains: eventType (always set to "intersection"), threshold (the visibility ratio that triggered the event), observeTime (SDK timestamp when observation began), showTime and showEndTime (defining the visibility window), params (custom metadata provided by the developer), and triggerPageUrl (the current page URL at event time). This comprehensive schema enables detailed analysis of element exposure duration and business context.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →