This repository was archived by the owner on Jan 15, 2026. It is now read-only.
forked from snowplow/snowplow-javascript-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
77 lines (69 loc) · 2.61 KB
/
Copy pathindex.ts
File metadata and controls
77 lines (69 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { BrowserPlugin, BrowserTracker, dispatchToTrackersInCollection } from '@snowplow/browser-tracker-core';
import { DynamicContext, buildSelfDescribingEvent, resolveDynamicContext } from '@snowplow/tracker-core';
import { WEB_VITALS_SCHEMA } from './schemata';
import { attachWebVitalsPageListeners, createWebVitalsScript, webVitalsListener } from './utils';
const _trackers: Record<string, BrowserTracker> = {};
const WEB_VITALS_SOURCE = 'https://unpkg.com/web-vitals@4/dist/web-vitals.iife.js';
let listenersAttached = false;
interface WebVitalsPluginOptions {
loadWebVitalsScript?: boolean;
webVitalsSource?: string;
context?: DynamicContext;
}
const defaultPluginOptions = {
loadWebVitalsScript: true,
webVitalsSource: WEB_VITALS_SOURCE,
context: [],
};
/**
* Adds Web Vitals measurement events
*
* @param pluginOptions.loadWebVitalsScript - Should the plugin immediately load the Core Web Vitals measurement script from UNPKG CDN.
* @param pluginOptions.webVitalsSource - The URL endpoint the Web Vitals script should be loaded from. Defaults to the UNPKG CDN.
* @remarks
*/
export function WebVitalsPlugin(pluginOptions: WebVitalsPluginOptions = defaultPluginOptions): BrowserPlugin {
const webVitalsObject: Record<string, unknown> = {};
const options = { ...defaultPluginOptions, ...pluginOptions };
let trackerId: string;
let webVitalsScript: HTMLScriptElement | undefined;
return {
activateBrowserPlugin: (tracker) => {
trackerId = tracker.id;
_trackers[trackerId] = tracker;
function sendWebVitals() {
if (!Object.keys(webVitalsObject).length) {
return;
}
dispatchToTrackersInCollection(Object.keys(_trackers), _trackers, (t) => {
t.core.track(
buildSelfDescribingEvent({
event: {
schema: WEB_VITALS_SCHEMA,
data: webVitalsObject,
},
}),
resolveDynamicContext(options.context ?? [], webVitalsObject)
);
});
}
if (options.loadWebVitalsScript) {
webVitalsScript = createWebVitalsScript(options.webVitalsSource);
}
/*
* Attach page listeners only once per page.
* Prevent multiple trackers from attaching listeners multiple times.
*/
if (!listenersAttached) {
if (webVitalsScript) {
webVitalsScript.addEventListener('load', () => webVitalsListener(webVitalsObject));
} else {
webVitalsListener(webVitalsObject);
}
attachWebVitalsPageListeners(sendWebVitals);
listenersAttached = true;
}
return;
},
};
}