GoogleChrome / web-vitals

Essential metrics for a healthy site.
https://web.dev/vitals
Apache License 2.0
7.62k stars 418 forks source link

【Discuss & May Performance Issue】whenIdle add never removed visibilitychange event listener #534

Closed youngBrain1893 closed 1 month ago

youngBrain1893 commented 2 months ago

I was just tried to collect LCP metric for my project,and when I just add onLCP for my project, I got an performance issue at the Performance monitor panel:the JS event listeners increased at every operate on the page and I tried to debug the code,and I got the code onLCP.ts#L103-L108 may case the performance issue

['keydown', 'click'].forEach((type) => {
        // Wrap in a setTimeout so the callback is run in a separate task
        // to avoid extending the keyboard/click handler to reduce INP impact
        // https://github.com/GoogleChrome/web-vitals/issues/383
        addEventListener(type, () => whenIdle(stopListening), true);
});
  1. it add click and keydown event, and the handler was wrapped with whenIdle
  2. whenIdle will call onHidden which will add visibilitychange listener when the page's visibilityState is not 'hidden', and will never be removed.
  3. each time the page (or tab for chrome) visibility change(hidden -> visible), the listeners will execute
click/keydown -> whenIdle process -> add visiblitychange listener(always increase never remove)

for the onINP each time the PerformanceObserve.observe('event') was fired, the handle function(handleEntries)call whenIdle which add a visiblitychange listener

It's a performance issue or designed?

tunetheweb commented 1 month ago

Unless I'm missing something, I think you might be right! I've raised #537 to fix this.