Measuring Cumulative Layout Shift (CLS) in WebPageTest
Tags: webdev, webperf, webpagetest
Published: 2019-07-18 21:36:45

---
title: Measuring Cumulative Layout Shift (CLS) in WebPageTest
published: true
description: Learn how to configure WebPageTest to extract layout instability insights
tags: webdev, webperf, webpagetest
cover_image: https://thepracticaldev.s3.amazonaws.com/i/7rdazpn638av0nrmwey5.png
---

# What is CLS?

Cumulative Layout Shift (CLS) is a relatively new metric to help you understand the [delightfulness](https://developers.google.com/web/fundamentals/performance/user-centric-performance-metrics#user-centric_performance_metrics) of the user experience. You might be reading a website when suddenly the text shifts down 100 pixels and you lose your place. That's not a delightful experience.

![A graphic showing text shifting down](https://web.dev/layout-instability-api/layout-shift-1.png)

The value of a layout shift is the percent of the viewport that moved. So in this example perhaps 10% of the viewport shifted. If another shift of 2% happens later, the page's CLS would be 12%.

# How can it be measured?

[web.dev/layout-instability/api](https://web.dev/layout-instability-api) is a great resource to learn more about the API and how to use it to measure CLS. Here's their example code to calculate CLS:

```js
// Stores the current layout shift score for the page.
let cumulativeLayoutShiftScore = 0;

// Detects new layout shift occurrences and updates the
// `cumulativeLayoutShiftScore` variable.
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    cumulativeLayoutShiftScore += entry.value;
  }
});

observer.observe({entryTypes: ['layoutShift']});

// Sends the final score to your analytics back end once
// the page's lifecycle state becomes hidden.
document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'hidden') {
    // Force any pending records to be dispatched.
    observer.takeRecords();

    // Send the final score to your analytics back end
    // (assumes `sendToAnalytics` is defined elsewhere).
    sendToAnalytics({cumulativeLayoutShiftScore});
  }
});
```

At the moment, the `layoutShift` type is only available when the API is explicitly enabled. If you're running Chrome 76 or newer, you can start it up via the command line with this flag set:

```
--enable-blink-features=LayoutInstabilityAPI
```

# Measuring CLS in WebPageTest

[WebPageTest](https://webpagetest.org) (WPT) is a popular tool for controlled measurements of web performance stats. Let's take a look at how we can configure it to record CLS.

## Choosing the right browser

![](https://thepracticaldev.s3.amazonaws.com/i/2kdlzdb70xoy1offzlj4.png)

WPT supports many browsers from many locations around the world. For this test to work, we need a newer version of Chrome that supports the `LayoutInstabilityAPI` Blink feature. Since WPT's default version of Chrome is on version 75 at this time of writing, we'll select Chrome Canary (version 77), which is available from the Dulles, VA test location.

## Setting the command line flag

![](https://thepracticaldev.s3.amazonaws.com/i/0ypjcoktsl7churljf9a.png)

Under the advanced settings "Chromium" tab there's a field to provide command line options.

## Measuring CLS as a custom metric

![](https://thepracticaldev.s3.amazonaws.com/i/1xm790hc4dwdtjjulnx3.png)

Custom metrics are snippets of JavaScript that execute as the web page test is wrapping up. The syntax is to give it a name in `[name]` format on the first line, followed by a script with a single return value. Here's a custom metric to measure CLS:

```js
[CumulativeLayoutShift]
return new Promise(resolve => {
  var CLS = 0;
  new PerformanceObserver(list => {
    list.getEntries().forEach(entry => {
      if (entry.hadRecentInput) return;
      CLS += entry.value;
    });
    resolve(CLS);
  }).observe({type: "layout-shift", buffered: true});
});
```

_Side note: Astute WPT mega-pro power users reading this post are objecting to this script because it returns a promise, and custom metrics only support synchronous code. Not anymore! As of literally [a couple hours ago](https://github.com/WPO-Foundation/wptagent/commit/19f88b560a55e2e31b718c89efdd9e72b432fb89), WPT now supports async custom metrics!_

This script will resolve to the CLS value for the test page, whose layout shifts have been saved to a buffer.

---

Ok! So with those options configured, you're ready to enter the URL of the page you want to test and run it. You can find the results on the [Custom Metrics](https://www.webpagetest.org/custom_metrics.php?test=190718_R6_69b9deac766918ca221a7c1b66326ed2&run=1&cached=0) page.

![](https://thepracticaldev.s3.amazonaws.com/i/y8ywcfpb2lmdn9r0da4a.png)

For this page, the CLS is `0.3`. It's a page I built, with a large part of its UI dynamically rendered from a script, so ~30% checks out.

![](https://thepracticaldev.s3.amazonaws.com/i/n2v6fbnng0zj02yxsujx.png)

To visualize this, we can use the [filmstrip view](https://www.webpagetest.org/video/compare.php?tests=190718_R6_69b9deac766918ca221a7c1b66326ed2-r:1-c:0), which shows us what the page looked like while it loaded. In this case it was blank for half a second, then the entire thing rendered. It's not clear where the layout shift is, but it could have happened in a matter of milliseconds. It isn't necessarily a poor user experience if the layout shift happens so close to the start of rendering, so that might be a case for tweaking the CLS algorithm.

# Wrapping up

CLS is still a very new metric, so if you do start using it, please leave any feedback on the [Layout Instability API GitHub repository](https://github.com/WICG/layout-instability).