Frontend Development 11 min read

Implementing Front‑end Exposure Tracking with a Custom Vue Directive

This article explains how to build a reliable front‑end exposure (view) tracking solution for e‑commerce pages by using the native IntersectionObserver API together with a custom Vue directive, covering the definition of effective exposure, required business rules, and complete code implementation.

政采云技术
政采云技术
政采云技术
Implementing Front‑end Exposure Tracking with a Custom Vue Directive

The article introduces data collection (buried point) techniques for web applications, focusing on three main types: page, click, and exposure tracking. Exposure tracking measures whether a UI element has actually been viewed by the user, which is essential for accurate click‑through‑rate calculations.

Effective Exposure

An exposure is considered effective when the product card is fully visible in the viewport, stays visible for at least 5 seconds, and is reported only once per page view. These rules prevent duplicate counts caused by rapid scrolling or repeated renders.

Detecting Visibility with IntersectionObserver

Instead of manually handling scroll events and calling Element.getBoundingClientRect() , the native IntersectionObserver API can asynchronously observe when a target element intersects the viewport. The observer is created with a configuration object containing root , rootMargin , and threshold fields.

let options = {
    root: document.querySelector('#scrollArea'),
    rootMargin: '0px',
    threshold: 1.0
}
let callback = (entries, observer) => {
  entries.forEach(entry => {});
};
let observer = new IntersectionObserver(callback, options);

The callback receives an array of IntersectionObserverEntry objects, each providing properties such as target , boundingClientRect , intersectionRatio , isIntersecting , rootBounds , and time . The observer can be controlled with observe() , unobserve() , disconnect() , and takeRecords() .

Vue Directive Implementation

A custom directive named visually is defined. When the directive is bound, it starts observing the element; when unbound, it stops observation. A list visuallyList stores IDs of already reported exposures to avoid duplication.

const options = {
    root: null, // default to viewport
    threshold: 1 // fire only when fully visible
}
const callback = (entries) => {
  entries.forEach(entry => {
    let visuallyData = null;
    try {
      visuallyData = JSON.parse(entry.target.getAttribute('visually-data'));
    } catch (e) {
      console.error('埋点数据格式异常', e);
      return;
    }
    if (!visuallyData) {
      observer.unobserve(entry.target);
      return;
    }
    if (entry.isIntersecting) {
      timer[visuallyData.id] = setTimeout(() => {
        sendUtm(visuallyData).then(res => {
          if (res.success) {
            observer.unobserve(entry.target);
            visuallyList.push(visuallyData.id);
            timer[visuallyData.id] = null;
          }
        });
      }, 5000);
    } else {
      if (timer[visuallyData.id]) {
        clearTimeout(timer[visuallyData.id]);
        timer[visuallyData.id] = null;
      }
    }
  });
};
let observer = new IntersectionObserver(callback, options);

Vue.directive('visually', {
  bind: (el, binding) => observer.observe(el),
  unbind: (el) => observer.unobserve(el)
});

A timer object ensures the element stays in view for the required 5 seconds before sending the tracking payload via sendUtm . After a successful report, the element is unobserved and its ID is added to visuallyList .

Polyfill and Usage

For browsers that do not support IntersectionObserver (e.g., older IE), a polyfill is imported with require('intersection-observer') . The directive can then be used in templates as follows:

<div v-visually="'visuallyData.id'" :visually-data="JSON.stringify(visuallyData)" class="browse"></div>

After installing the plugin via Vue.use() , any element with the visually directive will automatically report an exposure once it meets the defined criteria.

Conclusion

Accurate exposure tracking is crucial for reliable data analysis in e‑commerce. By combining the IntersectionObserver API with a Vue custom directive, developers can implement a performant, declarative solution that handles visibility detection, debounce logic, duplicate prevention, and cross‑browser compatibility.

frontendJavaScriptVueIntersectionObserverexposure trackingCustom Directive
政采云技术
Written by

政采云技术

ZCY Technology Team (Zero), based in Hangzhou, is a growth-oriented team passionate about technology and craftsmanship. With around 500 members, we are building comprehensive engineering, project management, and talent development systems. We are committed to innovation and creating a cloud service ecosystem for government and enterprise procurement. We look forward to your joining us.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.