Frontend Development 16 min read

Front‑End Tracking (埋点) Overview, Monitoring Types, Performance Metrics, and Implementation Guide

This article explains front‑end tracking concepts, outlines data, performance, and error monitoring, details common performance metrics, compares code‑based, visual, and automatic tracking solutions, and provides practical JavaScript snippets for event collection, error handling, page‑view reporting, and data transmission methods such as XHR, image GIF, and sendBeacon.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Front‑End Tracking (埋点) Overview, Monitoring Types, Performance Metrics, and Implementation Guide

Front‑end tracking (埋点) refers to inserting specific code into web pages or applications to collect user behavior data—clicks, page views, inputs—and send it to a server for analysis, enabling developers to understand and optimize user interactions.

The tracking workflow typically includes defining events, adding collection code, sending data, and analyzing results to uncover usage patterns and guide product improvements.

Front‑End Monitoring

Monitoring can be divided into three main categories:

Data monitoring : tracks PV, UV, stay time, entry sources, and user actions on each page.

Performance monitoring : measures load times, first paint, DNS resolution, TCP handshake, SSL handshake, response time, DOM parsing, and overall page render time.

Error monitoring : captures JavaScript runtime errors, resource loading failures, and unhandled promise rejections.

Performance Metrics

Key timing fields (derived from the Navigation Timing API) include unload , redirect , appCache , dns , tcp , ssl , response , dom , dcl , resources , domReady , first paint , first contentful paint , first interactive , first byte , load , etc., each calculated by subtracting start timestamps from end timestamps to reflect specific stages of page loading.

Tracking Solutions

Three common implementation approaches are:

Code‑based tracking : developers manually insert JavaScript at event points for precise data capture, offering high flexibility but requiring development effort.

Visual tracking : a UI lets non‑technical users select elements and events; the system generates the necessary code, reducing effort but limiting customizability.

Automatic (no‑trace) tracking : SDK automatically records all user interactions, minimizing manual work but potentially generating redundant data and increasing transmission overhead.

Data Collection Types

Collected data includes page‑view metrics (PV, UV, stay time), user behavior (clicks, scrolls, inputs), error information, user attributes (age, gender, location), device details (OS, browser), usage duration, and search keywords. These data help assess popularity, user preferences, debugging, marketing, and cross‑platform optimization.

Developing a Tracking SDK

The SDK typically handles three aspects: data monitoring, performance monitoring, and error monitoring, implemented via DOM event listeners, JavaScript error listeners, and PV reporters.

Example of a basic SDK skeleton:

export default class Tracker {
    private data: Options
    public constructor(option: Options) { ... }
    // DOM event reporting
    private domTracker() { ... }
    // JS error reporting
    private jsError() { ... }
    // PV reporting
    private pv() { ... }
    // Send data to backend
    private sendData
(data: T) { ... }
}

DOM Event Reporting

window.addEventListener('load', e => {
    const timing = window.performance.timing;
    const { domComplete, domLoading } = timing;
    const domTiming = domComplete - domLoading;
    console.log('domTiming: ', domTiming);

    const perEntries = window.performance.getEntries();
    const { domainLookupStart, domainLookupEnd } = perEntries[0];
    const dnsTiming = domainLookupEnd - domainLookupStart;
    console.log('dnsTiming: ', dnsTiming);

    const observer = new PerformanceObserver(list => {
        const entries = list.getEntries();
        entries.forEach(entry => {
            if (entry.name === 'first-paint') {
                console.log('First Paint:', entry.startTime);
            } else if (entry.name === 'first-contentful-paint') {
                console.log('First Contentful Paint:', entry.startTime);
            }
        });
    });
    observer.observe({ entryTypes: ['paint'] });
});

JavaScript Error Reporting

window.addEventListener('error', e => {
    console.log('e: ', e);
});
window.addEventListener('error', e => {
    e.preventDefault();
    const isErrorEvent = e instanceof ErrorEvent;
    if (!isErrorEvent) {
        this.sendData({ type: 'resource', msg: e.message });
        return;
    }
    this.sendData({ type: 'js', msg: e.message });
}, true);

Promise Rejection Reporting

window.addEventListener('unhandledrejection', (e: PromiseRejectionEvent) => {
    e.preventDefault();
    e.promise.catch(error => {
        const msg = error?.message || error;
        this.sendData({ type: 'promise', msg });
    });
});

Page‑View Reporting

Hash‑based routing can be monitored via the hashchange event:

window.addEventListener('hashchange', e => {
    this.sendData({ type: 'hash', msg: e });
});

History‑based routing requires overriding pushState and replaceState to dispatch custom events:

this.historyType.forEach(item => {
    const origin = history[item];
    const eventHistory = new Event(item);
    window.history[item] = function () {
        origin.apply(this, arguments);
        window.dispatchEvent(eventHistory);
    };
    window.addEventListener(item, () => {
        this.sendData({ type: 'history', msg: item });
    });
});

Custom events can be created and dispatched as follows:

const e = new Event('customEvent');
window.addEventListener('customEvent', e => {
    console.log('捕获自定义事件');
});
function btnClick() {
    window.dispatchEvent(e);
}

Data Transmission Methods

Common ways to send tracking data include:

XHR requests : simple HTTP POST/GET, but may face cross‑origin issues and data loss on page unload.

Image (GIF) beacon : creates an Image with a URL containing the data, avoiding CORS, lightweight, but limited by URL length and unsuitable for large payloads.

Navigator.sendBeacon() : asynchronous transmission that survives page unload, though browser support varies.

Example of using sendBeacon :

navigator.sendBeacon('http://127.0.0.1:5500/data', JSON.stringify({
    event: 'pageview',
    url: window.location.href,
    time: Date.now()
}));

These techniques together form a comprehensive front‑end tracking system that captures user interactions, performance characteristics, and errors, enabling data‑driven product optimization.

monitoringperformancetrackingweb-analytics
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

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.