Skip to content

Commit

Permalink
MWPW-159561 Add lcpSectionOne metric to web vitals (#3044)
Browse files Browse the repository at this point in the history
* MWPW-159561 Add lcpSectionOne metric

Logs if the LCP Element is in Section One of the page.

* PR Feedback
  • Loading branch information
chrischrischris authored Oct 30, 2024
1 parent fa39a05 commit 8f0adc1
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
8 changes: 6 additions & 2 deletions libs/utils/logWebVitals.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,18 +76,22 @@ function isFragmentFromMep(fragPath, mep) {
});
}

const boolStr = (val) => `${!!val}`;

function observeLCP(lanaData, delay, mep) {
const sectionOne = document.querySelector('main > div');
new PerformanceObserver((list) => {
const entries = list.getEntries();
const lastEntry = entries[entries.length - 1]; // Use the latest LCP candidate
lanaData.lcp = parseInt(lastEntry.startTime, 10);
const lcpEl = lastEntry.element;
lanaData.lcpElType = lcpEl.nodeName.toLowerCase();
lanaData.lcpEl = getElementInfo(lcpEl);
lanaData.lcpSectionOne = boolStr(sectionOne.contains(lcpEl));
const closestFrag = lcpEl.closest('.fragment');
lanaData.isFrag = closestFrag ? 'true' : 'false';
lanaData.isFrag = boolStr(closestFrag);
if (closestFrag) {
lanaData.isMep = isFragmentFromMep(closestFrag.dataset.path, mep) ? 'true' : 'false';
lanaData.isMep = boolStr(isFragmentFromMep(closestFrag.dataset.path, mep));
} else {
lanaData.isMep = 'false';
}
Expand Down
2 changes: 2 additions & 0 deletions test/utils/logWebVitalsUtils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ describe('Log Web Vitals Utils', () => {
expect(parseInt(vitals.lcp, 10)).to.be.greaterThan(1);
expect(vitals.lcpEl).to.be.equal('/test/utils/mocks/media_.png');
expect(vitals.lcpElType).to.be.equal('img');
expect(vitals.lcpSectionOne).to.be.equal('true');

expect(vitals.loggedIn).to.equal('false');
expect(vitals.os).to.be.oneOf(['mac', 'win', 'android', 'linux', '']);
expect(vitals.url).to.equal('localhost:2000/');
Expand Down

0 comments on commit 8f0adc1

Please sign in to comment.