Skip to content

Commit

Permalink
Cap TTFB in attribution
Browse files Browse the repository at this point in the history
  • Loading branch information
tunetheweb committed Mar 5, 2024
1 parent 8058a00 commit e8f254b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
14 changes: 13 additions & 1 deletion src/attribution/onFCP.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,21 @@ const attributeFCP = (metric: FCPMetric): void => {
const navigationEntry = getNavigationEntry();
const fcpEntry = metric.entries[metric.entries.length - 1];

// Should always have an fcpEntry to be able to attribute
if (!fcpEntry) return;

if (navigationEntry) {
const activationStart = navigationEntry.activationStart || 0;
const ttfb = Math.max(0, navigationEntry.responseStart - activationStart);
// Cap at 0 and ignore negative responseStart, future responseStart,
// or responseStart after LCP
const ttfb = Math.max(
0,
navigationEntry.responseStart <= 0 ||
navigationEntry.responseStart > performance.now() ||
navigationEntry.responseStart - activationStart > fcpEntry.startTime
? 0
: navigationEntry.responseStart - activationStart,
);

(metric as FCPMetricWithAttribution).attribution = {
timeToFirstByte: ttfb,
Expand Down
17 changes: 15 additions & 2 deletions src/attribution/onLCP.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,26 @@ const attributeLCP = (metric: LCPMetric) => {
if (navigationEntry) {
const activationStart = navigationEntry.activationStart || 0;
const lcpEntry = metric.entries[metric.entries.length - 1];

// Should always have an lcpEntry to be able to attribute
if (!lcpEntry) return;

const lcpResourceEntry =
lcpEntry.url &&
performance
.getEntriesByType('resource')
.filter((e) => e.name === lcpEntry.url)[0];

const ttfb = Math.max(0, navigationEntry.responseStart - activationStart);
// Cap at 0 and ignore negative responseStart, future responseStart,
// or responseStart after LCP
const ttfb = Math.max(
0,
navigationEntry.responseStart <= 0 ||
navigationEntry.responseStart > performance.now() ||
navigationEntry.responseStart - activationStart > lcpEntry.startTime
? 0
: navigationEntry.responseStart - activationStart,
);

const lcpRequestStart = Math.max(
ttfb,
Expand All @@ -55,7 +68,7 @@ const attributeLCP = (metric: LCPMetric) => {
);
const lcpRenderTime = Math.max(
lcpResponseEnd,
lcpEntry ? lcpEntry.startTime - activationStart : 0,
lcpEntry.startTime - activationStart,
);

const attribution: LCPAttribution = {
Expand Down

0 comments on commit e8f254b

Please sign in to comment.