Performance Hands-On 2 - Cumulative Layout Shift (CLS)

๐Ÿ“‹ Instructions

In this hands-on exercise, you will learn how to measure and optimize the Cumulative Layout Shift (CLS) metric using browser DevTools.

๐Ÿ” What is CLS?

Cumulative Layout Shift (CLS) measures the sum of all unexpected layout shifts that occur during the entire lifespan of a page. A layout shift occurs any time a visible element changes its position from one rendered frame to the next.

โšก Demo Section (with CLS Issues)

Experiencing Layout Shift

The content below has intentional layout shift issues. Watch what happens as resources load:

Some initial content that will shift around...

This is an advertisement that loads late!

It doesn't have reserved space.

This text will shift down when the ad appears above it. Try scrolling or clicking the button below to trigger the shift!

Optimized Version (No CLS)

Here's the same content with proper optimization to prevent layout shifts:

Some initial content with proper spacing...

This is an advertisement with reserved space!

It loads in a space we set aside for it.

This text won't shift because we've reserved space for the ad above.

CLS Measurements

๐Ÿงช Measuring CLS

  1. ๐Ÿ› ๏ธ Open the browser DevTools by pressing F12 or Ctrl+Shift+I (Windows/Linux) or Cmd+Opt+I (Mac).
  2. ๐Ÿ“Š Navigate to the "Performance" tab.
  3. ๐Ÿ”„ Click the "Reload" button (circular arrow) to start recording and reload the page.
  4. ๐Ÿ‘† Try clicking the "Trigger Layout Shift" button during recording.
  5. โฑ๏ธ After the page loads and shifts occur, stop the recording.
  6. ๐Ÿ” Look for the red rectangles in the "Experience" section, which indicate layout shifts.
  7. ๐Ÿ‘† Click on these layout shift markers to see details about the affected elements.
  8. ๐Ÿ“Š Check the "Layout Shift Regions" in the filmstrip view (colored rectangles appear where shifts occurred).

๐Ÿ› ๏ธ Common CLS Optimization Techniques

๐Ÿง‘โ€๐Ÿ’ป Try It Yourself!

Use the DevTools Elements panel to fix the layout shift in the problem demo:

  1. Add a fixed height to the .late-load-ad element
  2. Set min-height to reserve space
  3. Reload and observe the improvement in CLS

๐Ÿ“š Additional Resources