LayoutShift - Web APIs 编辑

The LayoutShift interface of the Layout Instability API provides insights into the stability of web pages based on movements of the elements on the page.

Properties

LayoutShift.value
Returns the impact fraction (fraction of the viewport that was shifted) times the distance fraction (distance moved as a fraction of viewport).
LayoutShift.hadRecentInput
Returns true if there was a user input in the past 500 milliseconds.
LayoutShift.lastInputTime
Returns the time of the most recent user input.
LayoutShift.sources
Returns an array of LayoutShiftAttribution objects with information on the elements that were shifted.

Methods

LayoutShift.toJSON()
Converts the properties to JSON.

Examples

The following example shows how to capture layout shifts and log them to the console.

Note that in this example data is only sent to the server when the user leaves the tab.

// Catch errors since some browsers throw when using the new `type` option.
// https://bugs.webkit.org/show_bug.cgi?id=209216
try {
  let cumulativeLayoutShiftScore = 0;

  const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    // Only count layout shifts without recent user input.
    if (!entry.hadRecentInput) {
      cumulativeLayoutShiftScore += entry.value;
    }
  }
  });

  observer.observe({type: 'layout-shift', buffered: true});

  document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'hidden') {
    // Force any pending records to be dispatched.
    observer.takeRecords();
    observer.disconnect();

    console.log('CLS:', cumulativeLayoutShiftScore);
  }
  });
} catch (e) {
  // Do nothing if the browser doesn't support this API.
}

Specifications

SpecificationStatusComment
Layout Instability API
The definition of 'LayoutShift' in that specification.
Editor's DraftInitial definition.

Browser compatibility

BCD tables only load in the browser

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:19 次

字数:4166

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文