How to Initialize Web-Tracing in a Vanilla JavaScript Project
To initialize web-tracing in a vanilla JavaScript project, import the init function from @web-tracing/core as an ES module and call it with a configuration object containing your dsn endpoint and appName.
The m-cheng-web/web-tracing repository provides a lightweight, framework-agnostic monitoring SDK that captures errors, performance metrics, and user interactions without requiring a build step. This guide explains how to initialize web-tracing in a vanilla JavaScript project using native ES modules, referencing the actual source implementation in packages/core/src/lib/exportMethods.ts.
What Happens When You Call init()
The init() function in packages/core/index.ts (exported from packages/core/src/lib/exportMethods.ts) performs a strict initialization sequence to prevent conflicts and ensure all monitors are properly instrumented:
- Duplicate initialization guard – The SDK checks
_global.__webTracingInit__and throws if the SDK is already initialized to prevent double-patching native APIs. - Options validation –
initOptions(options)parses the user-providedInitOptionsinterface and stores them in the internal_optionsobject. - Low-level patching –
initReplacemonkey-patchesXMLHttpRequest,fetch,addEventListener, and other browser APIs to intercept network and event data. - Utility initialization –
initBase,initSendData, andinitLineStatusset up the event bus, data buffering, and connection status detection. - Monitor activation – Individual modules for error, event, http, performance, pv (page view), intersection observer (exposure tracking), and optional screen recording are started.
- State marking – The SDK sets
_global.__webTracingInit__ = trueto lock the initialized state.
Minimal Setup Without a Bundler
You can load the SDK directly in an HTML file without webpack, vite, or any build tool. The official example at examples/vanilla/index.html demonstrates this pattern.
CDN-based ES Module Import
Use the JSDelivr CDN to import the core package as an ES module:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Web-Tracing Vanilla Demo</title>
</head>
<body>
<div id="app"></div>
<script type="module">
import { init } from "https://cdn.jsdelivr.net/npm/@web-tracing/core/dist/index.esm.js";
init({
dsn: "https://your-endpoint.example.com/track",
appName: "my-vanilla-app",
debug: true,
pv: true,
performance: true,
error: true,
event: true,
cacheMaxLength: 20,
cacheWatingTime: 1500
});
</script>
</body>
</html>
Key configuration options:
dsn(required): The endpoint URL where telemetry data is sent.appName(required): Identifier for your application in the dashboard.debug: Enables console logging for development.pv,performance,error,event: Boolean flags to toggle specific monitors.
Advanced Initialization Patterns
Delayed Initialization
For privacy compliance or performance optimization, you can delay initialization until user interaction. Expose a global helper function that calls init() on demand:
<script type="module">
import { init } from "https://cdn.jsdelivr.net/npm/@web-tracing/core/dist/index.esm.js";
window.startTracing = () => {
init({
dsn: "https://your-endpoint.example.com/track",
appName: "my-vanilla-app",
debug: true,
pv: true,
performance: true,
error: true,
event: true
});
};
</script>
<button onclick="startTracing()">Initialize Web-Tracing</button>
Manual Cache Management
When you need to force-send cached events or handle storage overflow, use the utility functions from packages/core/src/lib/sendData.ts:
import { sendLocal, setLocalizationOverFlow } from "https://cdn.jsdelivr.net/npm/@web-tracing/core/dist/index.esm.js";
setLocalizationOverFlow((data) => {
console.warn("Cache overflow – sending now", data);
});
sendLocal();
Core Architecture and Source Files
Understanding the internal structure helps with debugging and custom builds:
packages/core/index.ts– Public API surface exportinginit,destroyTracing,InitOptions, and utility methods.packages/core/src/lib/replace.ts– ContainsinitReplacewhich patches native browser APIs (XMLHttpRequest,fetch,addEventListener).packages/core/src/lib/base.ts– Initializes global objects, error utilities, and the internal event bus viainitBase.packages/core/src/lib/sendData.ts– Implements data buffering and thesendLocalfunction; handles thecacheMaxLengthandcacheWatingTimelogic.packages/core/src/lib/error.ts– Global error capture implementation.packages/core/src/lib/event.ts– DOM event tracking and event listener patching.packages/core/src/lib/http.ts– HTTP request monitoring built on top of the patched fetch/XHR.packages/core/src/lib/performance.ts– Resource timing and navigation performance collection.packages/core/src/lib/pv.ts– Page view tracking and SPA route change detection.
Summary
- Use ES modules: Load
@web-tracing/corevia CDN using<script type="module">to avoid bundler complexity. - Call
init()once: The SDK guards against duplicate initialization using_global.__webTracingInit__; subsequent calls will throw. - Provide required options: At minimum, specify
dsnandappNamein yourInitOptionsconfiguration. - Leverage utilities: Use
sendLocal()to flush cached data manually anddestroyTracing()to clean up listeners when needed. - Reference source: All logic resides in
packages/core/src/lib/with the entry point atpackages/core/index.ts.
Frequently Asked Questions
Can I use web-tracing without a CDN or npm?
Yes. Download the index.esm.js file from the CDN or build the repository from source, then serve it locally alongside your static assets. Import the local path in your module script: import { init } from './web-tracing/index.esm.js'.
What is the minimal required configuration to initialize web-tracing?
The init() function requires at least a dsn (your data collection endpoint) and an appName (application identifier). All other options in the InitOptions interface are optional and default to sensible production values.
How does the SDK prevent duplicate initialization?
The init() function checks _global.__webTracingInit__ before executing. If this flag is already true, the SDK throws an error to prevent double-patching of XMLHttpRequest and fetch, which would cause infinite loops and memory leaks.
Can I delay initialization until after user consent?
Yes. Defer the init() call until a user interaction or consent signal. Wrap the initialization in a function exposed to the global scope (e.g., window.startTracing) and invoke it only after the user accepts your tracking policy, as shown in the delayed initialization pattern above.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →