sdk: debounce screen views 50ms to avoid duplicated screen views
This commit is contained in:
@@ -20,6 +20,7 @@ function toCamelCase(str: string) {
|
||||
|
||||
export class Openpanel extends OpenpanelSdk<OpenpanelOptions> {
|
||||
private lastPath = '';
|
||||
private debounceTimer: number | undefined;
|
||||
|
||||
constructor(options: OpenpanelOptions) {
|
||||
super(options);
|
||||
@@ -43,6 +44,11 @@ export class Openpanel extends OpenpanelSdk<OpenpanelOptions> {
|
||||
}
|
||||
}
|
||||
|
||||
private debounce(func: () => void, delay: number) {
|
||||
clearTimeout(this.debounceTimer);
|
||||
this.debounceTimer = setTimeout(func, delay);
|
||||
}
|
||||
|
||||
private isServer() {
|
||||
return typeof document === 'undefined';
|
||||
}
|
||||
@@ -92,20 +98,20 @@ export class Openpanel extends OpenpanelSdk<OpenpanelOptions> {
|
||||
return ret;
|
||||
};
|
||||
|
||||
window.addEventListener('popstate', () =>
|
||||
window.dispatchEvent(new Event('locationchange'))
|
||||
);
|
||||
window.addEventListener('popstate', function () {
|
||||
window.dispatchEvent(new Event('locationchange'));
|
||||
});
|
||||
|
||||
const eventHandler = () => this.debounce(() => this.screenView(), 50);
|
||||
|
||||
if (this.options.hash) {
|
||||
window.addEventListener('hashchange', () => this.screenView());
|
||||
window.addEventListener('hashchange', eventHandler);
|
||||
} else {
|
||||
window.addEventListener('locationchange', () => this.screenView());
|
||||
window.addEventListener('locationchange', eventHandler);
|
||||
}
|
||||
|
||||
// give time for setProfile to be called
|
||||
setTimeout(() => {
|
||||
this.screenView();
|
||||
}, 50);
|
||||
setTimeout(() => eventHandler(), 50);
|
||||
}
|
||||
|
||||
public trackAttributes() {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"module": "index.ts",
|
||||
"scripts": {
|
||||
"build": "rm -rf dist && tsup",
|
||||
"build-for-openpanel": "pnpm build && cp dist/cdn.global.js ../../../apps/public/public/op.js && cp dist/cdn.global.js ../../../apps/test/public/op.js",
|
||||
"build-for-openpanel": "pnpm build && cp dist/cdn.global.js ../../../apps/public/public/op.js",
|
||||
"lint": "eslint .",
|
||||
"format": "prettier --check \"**/*.{mjs,ts,md,json}\"",
|
||||
"typecheck": "tsc --noEmit"
|
||||
|
||||
Reference in New Issue
Block a user