Skip to content

Commit

Permalink
Metrics: Tag CLS elements
Browse files Browse the repository at this point in the history
This will help people dig into pages with bad layout shifts

Co-authored-by: Alberto Leal <[email protected]>
  • Loading branch information
jarstelfox and dashed committed Jun 22, 2021
1 parent 688a986 commit 741a3f1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
11 changes: 10 additions & 1 deletion packages/tracing/src/browser/metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { browserPerformanceTimeOrigin, getGlobalObject, htmlTreeAsString, isNode
import { Span } from '../span';
import { Transaction } from '../transaction';
import { msToSec } from '../utils';
import { getCLS } from './web-vitals/getCLS';
import { getCLS, LayoutShift } from './web-vitals/getCLS';
import { getFID } from './web-vitals/getFID';
import { getLCP, LargestContentfulPaint } from './web-vitals/getLCP';
import { getFirstHidden } from './web-vitals/lib/getFirstHidden';
Expand All @@ -20,6 +20,7 @@ export class MetricsInstrumentation {

private _performanceCursor: number = 0;
private _lcpEntry: LargestContentfulPaint | undefined;
private _clsEntry: LayoutShift | undefined;

public constructor() {
if (!isNodeEnv() && global?.performance) {
Expand Down Expand Up @@ -207,6 +208,13 @@ export class MetricsInstrumentation {

transaction.setTag('lcp.size', this._lcpEntry.size);
}

if (this._clsEntry) {
logger.log('[Measurements] Adding CLS Data');
transaction.setData('measurements.cls', {
sources: this._clsEntry.sources.map(source => htmlTreeAsString(source.node)),
});
}
}
}

Expand All @@ -221,6 +229,7 @@ export class MetricsInstrumentation {

logger.log('[Measurements] Adding CLS');
this._measurements['cls'] = { value: metric.value };
this._clsEntry = entry as LayoutShift;
});
}

Expand Down
10 changes: 9 additions & 1 deletion packages/tracing/src/browser/web-vitals/getCLS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,17 @@ import { onHidden } from './lib/onHidden';
import { ReportHandler } from './types';

// https://wicg.github.io/layout-instability/#sec-layout-shift
interface LayoutShift extends PerformanceEntry {
export interface LayoutShift extends PerformanceEntry {
value: number;
hadRecentInput: boolean;
sources: Array<LayoutShiftAttribution>;
toJSON(): Record<string, unknown>;
}

export interface LayoutShiftAttribution {
node?: Node;
previousRect: DOMRectReadOnly;
currentRect: DOMRectReadOnly;
}

export const getCLS = (onReport: ReportHandler, reportAllChanges = false): void => {
Expand Down

0 comments on commit 741a3f1

Please sign in to comment.