Cumulative Layout Shift (CLS) is a vital performance metric that measures the unexpected shifting of visual elements on a web page while it's loading or even after it's fully loaded. These shifts can be frustrating for users, as they may cause misclicks or make reading content more challenging.
Let's break down what CLS is, why it matters, and how you can improve it:
1. What is Cumulative Layout Shift?
Layout Shift: A layout shift occurs when a visible element changes its position from one rendered frame to the next.
Cumulative: It's the sum of all individual layout shift scores for every unexpected layout shift that occurs during the entire lifespan of the page.
2. Why Does CLS Matter?
User Experience: Unexpected layout shifts can lead to a frustrating user experience. For instance, if a user is reading an article and a large image suddenly loads above the text, pushing it down, it disrupts the reading flow.
SEO Impact: Google considers CLS as one of the Core Web Vitals, meaning that it can influence your website's ranking in search results.
3. How is CLS Calculated?
Impact Fraction: Measures how unstable elements impact the viewport between two frames.
Distance Fraction: Measures the distance unstable elements have moved relative to the viewport.
CLS Score: The product of impact fraction and distance fraction for all unexpected shifts.
4. How to Improve CLS?
Reserve Space for Media: Use width and height attributes for images, videos, or other media elements so the browser knows exactly how much space to allocate before the item is fully loaded.
Avoid Inserting New Content Above Existing Content: Unless it's a response to user interaction, avoid adding new elements above existing ones, especially after the page starts loading.
Use Web Fonts Wisely: If using custom fonts, consider strategies to minimize their impact on layout shifts, like using
font-display: optional
.Prevent Shifts with Ads and Embeds: For ads or third-party embeds, try to use a reserved space that matches the size of the content, or consider loading them off-screen and bringing them into view only when ready.
Test Across Devices: Different devices and screen sizes may experience different layout shifts, so be sure to test your site's CLS across various devices and conditions.
Conclusion
Cumulative Layout Shift is all about stability and predictability on a web page. Improving CLS ensures a more pleasant and engaging user experience, leading to potentially higher user retention and better SEO rankings.