Skip to content

Commit

Permalink
feat: change webvitals to batch
Browse files Browse the repository at this point in the history
  • Loading branch information
renanccastro committed Feb 7, 2024
1 parent 3c263e0 commit ee888e0
Showing 1 changed file with 32 additions and 17 deletions.
49 changes: 32 additions & 17 deletions lib/client/models/webVitals.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,36 +3,51 @@ import { getClientArch, getBrowserInfo } from '../utils';
import { onCLS, onFCP, onFID, onINP, onLCP, onTTFB } from 'web-vitals';

export class WebVitalsModel {
queue = new Set();
addToQueue (metric) {
this.queue.add({ metric: metric.value, matricName: metric.name });
}

flushQueue () {
if (this.queue.size > 0) {
Kadira.send(this._buildPayload([...this.queue]), '/client-metrics');
this.queue.clear();
}
}

startTracking () {
const sender = (metric) =>
Kadira.send(
this._buildPayload({
metric: { value: metric.value, rating: metric.rating },
metricName: metric.name,
}),
'/client-metrics'
);
onCLS(sender);
onFCP(sender);
onFID(sender);
onINP(sender);
onLCP(sender);
onTTFB(sender);
const bindedAddToQueue = this.addToQueue.bind(this);
onFCP(bindedAddToQueue);
onFID(bindedAddToQueue);
onINP(bindedAddToQueue);
onLCP(bindedAddToQueue);
onTTFB(bindedAddToQueue);
onCLS(bindedAddToQueue);
// Report all available metrics whenever the page is backgrounded or unloaded.
addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
this.flushQueue();
}
});

// NOTE: Safari does not reliably fire the `visibilitychange` event when the
// page is being unloaded. If Safari support is needed, you should also flush
// the queue in the `pagehide` event.
addEventListener('pagehide', () => this.flushQueue());
}
constructor (options) {
options = options || {};

this.options = options;
}
_buildPayload = function ({ metric, metricName }) {
_buildPayload = function (metrics) {
const arch = getClientArch();
const browserInfo = getBrowserInfo();

return {
host: Kadira.options.hostname,
recordIPAddress: Kadira.options.recordIPAddress,
metricName,
metric,
metrics,
...browserInfo,
arch,
legacy: arch.endsWith('.legacy'),
Expand Down

0 comments on commit ee888e0

Please sign in to comment.