LCP目前是由 WICG(W3C Web平台孵化器社区组)提出的一项新特性,目前还不是W3C正式规范。我们可以通过 Chrome 的 PerformanceObserver API 计算它。
// Create a variable to hold the latest LCP value (since it can change).let lcp;// Create the PerformanceObserver instance.const po = new PerformanceObserver((entryList) => {const entries = entryList.getEntries();const lastEntry = entries[entries.length - 1];// Update `lcp` to the latest value, using `renderTime` if it's available,// otherwise using `loadTime`. (Note: `renderTime` may not be available if// the element is an image and it's loaded cross-origin without the// `Timing-Allow-Origin` header.)lcp = lastEntry.renderTime || lastEntry.loadTime;});// Observe entries of type `largest-contentful-paint`, including buffered// entries, i.e. entries that occurred before calling `observe()`.po.observe({type: 'largest-contentful-paint', buffered: true});// Send the latest LCP value to your analytics server once the user// leaves the tab.addEventListener('visibilitychange', function fn() {if (lcp && document.visibilityState === 'hidden') {console.log('LCP:', lcp);removeEventListener('visibilitychange', fn, true);}}, true);复制代码
用户体验的第三个问题“可以使用吗”可以用 TTI(Time to Interactive) 查看,它表示你的页面何时可以自由响应用户交互。它和 FMP 一样还不是 W3C 规范,也没有获取它的标准的 API,但 Google 提供了一个 TTI 的 polyfill 可以用来检测,你也可以用 lighthouse 获取 TTI。
