# How to Initialize Web-Tracing in a Vanilla JavaScript Project

> Easily initialize web tracing in your vanilla JavaScript project. Import the init function from @web-tracing/core and configure your DSN and app name for seamless performance monitoring.

- Repository: [m-cheng-web/web-tracing](https://github.com/m-cheng-web/web-tracing)
- Tags: getting-started
- Published: 2026-03-06

---

**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`](https://github.com/m-cheng-web/web-tracing/blob/main/packages/core/src/lib/exportMethods.ts).

## What Happens When You Call init()

The `init()` function in [`packages/core/index.ts`](https://github.com/m-cheng-web/web-tracing/blob/main/packages/core/index.ts) (exported from [`packages/core/src/lib/exportMethods.ts`](https://github.com/m-cheng-web/web-tracing/blob/main/packages/core/src/lib/exportMethods.ts)) performs a strict initialization sequence to prevent conflicts and ensure all monitors are properly instrumented:

1. **Duplicate initialization guard** – The SDK checks `_global.__webTracingInit__` and throws if the SDK is already initialized to prevent double-patching native APIs.
2. **Options validation** – `initOptions(options)` parses the user-provided `InitOptions` interface and stores them in the internal `_options` object.
3. **Low-level patching** – `initReplace` monkey-patches `XMLHttpRequest`, `fetch`, `addEventListener`, and other browser APIs to intercept network and event data.
4. **Utility initialization** – `initBase`, `initSendData`, and `initLineStatus` set up the event bus, data buffering, and connection status detection.
5. **Monitor activation** – Individual modules for **error**, **event**, **http**, **performance**, **pv** (page view), **intersection observer** (exposure tracking), and optional screen recording are started.
6. **State marking** – The SDK sets `_global.__webTracingInit__ = true` to 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`](https://github.com/m-cheng-web/web-tracing/blob/main/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:

```html
<!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:

```html
<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`](https://github.com/m-cheng-web/web-tracing/blob/main/packages/core/src/lib/sendData.ts):

```javascript
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`](https://github.com/m-cheng-web/web-tracing/blob/main/packages/core/index.ts)** – Public API surface exporting `init`, `destroyTracing`, `InitOptions`, and utility methods.
- **[`packages/core/src/lib/replace.ts`](https://github.com/m-cheng-web/web-tracing/blob/main/packages/core/src/lib/replace.ts)** – Contains `initReplace` which patches native browser APIs (`XMLHttpRequest`, `fetch`, `addEventListener`).
- **[`packages/core/src/lib/base.ts`](https://github.com/m-cheng-web/web-tracing/blob/main/packages/core/src/lib/base.ts)** – Initializes global objects, error utilities, and the internal event bus via `initBase`.
- **[`packages/core/src/lib/sendData.ts`](https://github.com/m-cheng-web/web-tracing/blob/main/packages/core/src/lib/sendData.ts)** – Implements data buffering and the `sendLocal` function; handles the `cacheMaxLength` and `cacheWatingTime` logic.
- **[`packages/core/src/lib/error.ts`](https://github.com/m-cheng-web/web-tracing/blob/main/packages/core/src/lib/error.ts)** – Global error capture implementation.
- **[`packages/core/src/lib/event.ts`](https://github.com/m-cheng-web/web-tracing/blob/main/packages/core/src/lib/event.ts)** – DOM event tracking and event listener patching.
- **[`packages/core/src/lib/http.ts`](https://github.com/m-cheng-web/web-tracing/blob/main/packages/core/src/lib/http.ts)** – HTTP request monitoring built on top of the patched fetch/XHR.
- **[`packages/core/src/lib/performance.ts`](https://github.com/m-cheng-web/web-tracing/blob/main/packages/core/src/lib/performance.ts)** – Resource timing and navigation performance collection.
- **[`packages/core/src/lib/pv.ts`](https://github.com/m-cheng-web/web-tracing/blob/main/packages/core/src/lib/pv.ts)** – Page view tracking and SPA route change detection.

## Summary

- **Use ES modules**: Load `@web-tracing/core` via 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 `dsn` and `appName` in your `InitOptions` configuration.
- **Leverage utilities**: Use `sendLocal()` to flush cached data manually and `destroyTracing()` to clean up listeners when needed.
- **Reference source**: All logic resides in `packages/core/src/lib/` with the entry point at [`packages/core/index.ts`](https://github.com/m-cheng-web/web-tracing/blob/main/packages/core/index.ts).

## Frequently Asked Questions

### Can I use web-tracing without a CDN or npm?

Yes. Download the [`index.esm.js`](https://github.com/m-cheng-web/web-tracing/blob/main/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.