Skip to content

Commit

Permalink
Update web-vitals and add TTFB
Browse files Browse the repository at this point in the history
  • Loading branch information
philipwalton committed Nov 12, 2021
1 parent 380f197 commit e1e3cb2
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 53 deletions.
75 changes: 27 additions & 48 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -53,6 +53,6 @@
"rollup": "^2.50.5",
"rollup-plugin-terser": "^7.0.2",
"superstatic": "^7.1.0",
"web-vitals": "^2.0.0"
"web-vitals": "^2.1.2"
}
}
23 changes: 19 additions & 4 deletions src/js/analytics.js
Expand Up @@ -16,12 +16,12 @@

/* global gtag */

import {getCLS, getFCP, getFID, getLCP} from 'web-vitals';
import {getCLS, getFCP, getFID, getLCP, getTTFB} from 'web-vitals';
import {getSegmentNameById} from './api.js';

const getConfig = (id) => {
const config = {
measurement_version: '6',
measurement_version: '7',
page_path: location.pathname,
};

Expand Down Expand Up @@ -53,6 +53,7 @@ const thresholds = {
FCP: [1800, 3000],
FID: [100, 300],
LCP: [2500, 4000],
TTFB: [800, 1800],
};

function getRating(value, thresholds) {
Expand Down Expand Up @@ -137,7 +138,7 @@ function getDebugInfo(name, entries = []) {
}

function handleMetric({name, value, delta, id, entries}) {
gtag('event', name, {
const params = {
value: Math.round(name === 'CLS' ? delta * 1000 : delta),
event_category: 'Web Vitals',
event_label: id,
Expand All @@ -146,14 +147,28 @@ function handleMetric({name, value, delta, id, entries}) {
metric_rating: getRating(value, thresholds[name]),
non_interaction: true,
...getDebugInfo(name, entries),
});
};

if (name === 'TTFB' && entries.length) {
const navEntry = entries[0];
Object.assign(params, {
fetch_start: navEntry.fetchStart,
domain_lookup_start: navEntry.domainLookupStart,
connect_start: navEntry.connectStart,
request_start: navEntry.requestStart,
response_start: navEntry.responseStart,
});
}

gtag('event', name, params);
}

export function measureWebVitals() {
getCLS(handleMetric);
getFCP(handleMetric);
getFID(handleMetric);
getLCP(handleMetric);
getTTFB(handleMetric);
}

function anonymizeSegment(id) {
Expand Down

0 comments on commit e1e3cb2

Please sign in to comment.