LCP目前是由 WICG(W3C Web平台孵化器社区组)提出的一项新特性,目前还不是W3C正式规范。我们可以通过 Chrome 的 PerformanceObserver API 计算它。

    1. // Create a variable to hold the latest LCP value (since it can change).
    2. let lcp;
    3. // Create the PerformanceObserver instance.
    4. const po = new PerformanceObserver((entryList) => {
    5. const entries = entryList.getEntries();
    6. const lastEntry = entries[entries.length - 1];
    7. // Update `lcp` to the latest value, using `renderTime` if it's available,
    8. // otherwise using `loadTime`. (Note: `renderTime` may not be available if
    9. // the element is an image and it's loaded cross-origin without the
    10. // `Timing-Allow-Origin` header.)
    11. lcp = lastEntry.renderTime || lastEntry.loadTime;
    12. });
    13. // Observe entries of type `largest-contentful-paint`, including buffered
    14. // entries, i.e. entries that occurred before calling `observe()`.
    15. po.observe({type: 'largest-contentful-paint', buffered: true});
    16. // Send the latest LCP value to your analytics server once the user
    17. // leaves the tab.
    18. addEventListener('visibilitychange', function fn() {
    19. if (lcp && document.visibilityState === 'hidden') {
    20. console.log('LCP:', lcp);
    21. removeEventListener('visibilitychange', fn, true);
    22. }
    23. }, true);
    24. 复制代码

    用户体验的第三个问题“可以使用吗”可以用 TTI(Time to Interactive) 查看,它表示你的页面何时可以自由响应用户交互。它和 FMP 一样还不是 W3C 规范,也没有获取它的标准的 API,但 Google 提供了一个 TTI 的 polyfill 可以用来检测,你也可以用 lighthouse 获取 TTI。