LayoutShift

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

特性

LayoutShift.value
返回 impact fraction (fraction of the viewport that was shifted) times the distance fraction (distance moved as a fraction of viewport).
LayoutShift.hadRecentInput
返回 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.

方法

LayoutShift.toJSON()
Converts the properties to JSON.

范例

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.
}
					

规范

规范 状态 Comment
Layout Instability API
The definition of 'LayoutShift' in that specification.
编者草案 初始定义。

浏览器兼容性

更新 GitHub 上的兼容性数据
Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
LayoutShift
Chrome 77 Edge 80 Firefox No IE No Opera Yes Safari No WebView Android 77 Chrome Android 77 Firefox Android No Opera Android Yes Safari iOS No Samsung Internet Android 12.0
hadRecentInput
Chrome 77 Edge 80 Firefox No IE No Opera Yes Safari No WebView Android 77 Chrome Android 77 Firefox Android No Opera Android Yes Safari iOS No Samsung Internet Android 12.0
lastInputTime
Chrome 77 Edge 80 Firefox No IE No Opera Yes Safari No WebView Android 77 Chrome Android 77 Firefox Android No Opera Android Yes Safari iOS No Samsung Internet Android 12.0
toJSON
Chrome 77 Edge 80 Firefox No IE No Opera Yes Safari No WebView Android 77 Chrome Android 77 Firefox Android No Opera Android Yes Safari iOS No Samsung Internet Android 12.0
value
Chrome 77 Edge 80 Firefox No IE No Opera Yes Safari No WebView Android 77 Chrome Android 77 Firefox Android No Opera Android Yes Safari iOS No Samsung Internet Android 12.0

图例

完整支持
完整支持
不支持
不支持
实验。期望将来行为有所改变。
实验。期望将来行为有所改变。