20i
How to fix cumulative layout shift

How to Fix Cumulative Layout Shift (CLS)

Cumulative Layout Shift (CLS) measures the stability of content on a web page during load.

It quantifies how much content shifts around as page elements load or change size.  

A poor CLS score can negatively affect the performance of your website in several ways: 

  • Frustrating and jarring browsing: Users expect content to remain stable as a page loads. When elements jump around or change position as assets load in, it creates a jarring, frustrating experience. This makes the site feel broken, amateurishly built, or slow. 
  • Confusion and disorientation: Sudden layout shifts force users to re-scan and re-focus on content. This interrupts their browsing flow and makes it harder to absorb information. 
  • Slower comprehension: Studies show users comprehend less when content jumps around unpredictably. Layout shifts slow down processing speed and retention. 
  • Increased abandonment: Sites with excessive layout shift have higher bounce rates, as users leave due to a clunky experience, which contributes to perceived site unreliability. 
  • Lower conversion rates: By hurting comprehension and retention, CLS directly reduces conversions for sites dependent on conveying information. 
  • Reduced Search Rankings: As CLS is part of Google’s core web vitals, it is also a Google ranking factor. If a website has large amounts of layout shift, it may receive less favourable search rankings when competing with websites that don’t have these issues. 

In this post we’ll delve in to the steps that you can take to fix these issues and prevent them from reoccurring in the future. 

Note: A lot of the CSS/JavaScript and Image optimisation techniques we list below can be done within My20i with just a few clicks, using our free Website Acceleration Suite.

Use Correct Image Dimensions  

Specify `width` and `height` attributes on `<img>` tags. This reserves space in the document layout before images load and prevents layout shifts.

Be sure to use accurate dimensions that match the true size of the image. 

<img src="image.jpg" width="500" height="300"> 

This also applies to images which are lazy loaded off screen. 

Compress Images 

All images that you upload to your website should be optimised to reduce file size.

Use image compression tools, and lightweight image formats such as WebP, SVG or JPEG to ensure that images load quickly. 

Smaller image files load faster and reduce CLS from delayed image loading. 

Font Loading Strategies 

Fonts can also delay initial rendering and cause layout shifts as they load. The following strategies can help prevent this. 

Preload Fonts and Use Font-display  

Preloading web fonts with ‘<link rel=”preload”>’ ensures they are fetched early and allows you to use `font-display` to control rendering behaviour.

Set ‘font-display: swap’ to show fallback fonts until the web font loads to avoid layout shifts. 

System fonts like Arial and Times New Roman don’t require a network request. Use system fonts for your initial render to improve performance.

You can add preferred web fonts lower in the CSS cascade to take over once loaded. This provides a smooth transition between system and web fonts. 

Additional Tips: 

  • Subset fonts to only include the glyph ranges needed. This reduces font file size. 
  • Use variable fonts which combine multiple fonts into a single file.   
  • Load font files from same domain as CSS for better caching. 
  • Compress font files and enable Brotli compression on the server. 

Video and Embeds Handling 

As with images, setting explicit dimensions for video and iframe elements can help avoid CLS issues.

Without defined dimensions, the browser won’t reserve space for the embed and it will cause a shift when loading in.   

Use the width and height attributes to set the dimensions for videos and iframes based on their true size: 

<iframe width="560" height="315" src="..."></iframe> 
<video width="560" height="315" src="..."></video> 

The aspect ratio placeholder technique is another option to reserve space for embeds before they load.

This involves wrapping the video or iframe in a container div that uses padding-top with a percentage matching the aspect ratio. 

For a 16:9 video: 

<div class="ratio-box" style="padding-top: 56.25%"> 
  <iframe src="..."></iframe>
</div> 

This allows the div to take up width normally while reserving the proper height. When the embed loads in, it will fill the prepared space rather than cause a shift. 

Avoiding Third-Party Widgets 

Limiting or asynchronously loading third-party widgets like social media buttons, chat plugins, or embedded maps can prevent layout shifts.

These elements often load after the initial render, causing objects to suddenly appear and push down content. 

Consider replacing third-party widgets with first-party alternatives you have more control over. For example: 

  • Show social media share links instead of full embed widgets. 
  • Replace chat plugins with a simple contact form. 
  • Use a static image map instead of an interactive one, then enhance it with JavaScript only for users that need it.   

Prioritise your core content first, then enhance the page with non-essential elements loaded asynchronously.

Load these widgets using `async` or `defer` attributes, or dynamically inject them after the page finishes loading.

Limit these features down to what brings real value for your readers. Every unnecessary embed has performance costs. 

Optimising CSS 

CSS files can significantly impact your CLS score if not optimised properly. Render-blocking CSS in the document head can delay initial page render, while excess unused CSS bloats files sizes and increased loading times. 

To optimise your CSS and improve CLS: 

  • Inline critical CSS: Extract the minimal set of CSS required for the initial page render and inline it directly in the HTML document head. This eliminates an extra roundtrip request and allows the page to construct the critical above-the-fold content immediately. Non-critical CSS can be lazy loaded after page load. 
  • Minimise unused CSS rules: Audit your CSS files and remove any outdated, duplicate or unnecessary rules. Unused CSS still impacts page load times, so eliminating bloat improves performance. Consider automating this process through build tools. 
  • Avoid render-blocking resources: Resources loaded in the document head block rendering while they load. Defer non-critical external stylesheets and fonts using rel=”preload” or rel=”preload” to allow earlier page render. 
  • Minify CSS: Minification tools remove whitespace, comments and optimises CSS files for faster delivery and parsing. Enable minification through your build process for production sites. 
  • Reduce specificity: Use simpler CSS selectors where possible to avoid over-specificity. This simplifies stylesheets and avoids unexpected cascade conflicts. 
At 20i, all the websites we host go through our free website acceleration suite, to minify code such as CSS, and reduce network payload/ load websites faster. 

JavaScript Load Management 

As with CSS, managing when and how JavaScript files are loaded is crucial for minimising CLS.

There are two main techniques for this: 

Load Scripts Asynchronously 

The best practice is to load any non-essential JavaScript asynchronously. This allows the HTML and critical CSS/content to load first before the JavaScript. 

To load a script async in HTML, add `async` to the script tag: 

<script async src="script.js"></script>  

This tells the browser to download the script without blocking the HTML parsing. The script will execute as soon as it finishes downloading. 

Defer Non-Critical Scripts 

For scripts that need to execute in order, but don’t need to block initial HTML parsing, use `defer` instead: 

<script defer src="script.js"></script> 

This also downloads the script asynchronously, but will only execute after the HTML document has finished parsing. This ensures dependencies are met before execution. 

Defer is great for things like analytics scripts that don’t need to block the initial render. 

Optimise JavaScript Code  

Besides loading strategies, make sure the JavaScript code itself is optimised to avoid expensive operations that could shift layout: 

  • Avoid unnecessary DOM manipulations, especially on first load. 
  • Use requestAnimationFrame for visual updates. 
  • Load JavaScript lazily when some components are needed. 
  • Split code into smaller chunks that can be loaded on-demand. 
JavaScript minification is also something handled automatically by the 20i web acceleration suite. 

Testing Your Fixes 

After making changes to improve CLS, you’ll want to test and verify that your fixes are working. Here are some tips for testing and validating CLS improvements: 

Use Lighthouse 

The easiest way to test for CLS improvements is to run Lighthouse in Chrome DevTools. Lighthouse provides the previously mentioned numeric CLS score, with lower scores being better. Run an audit before and after making changes to quantify any improvements.  

Pagespeed Insights 

You can also run this report with Google PageSpeed insights, which uses the same technology as Lighthouse, but on a more user-friendly platform. 

Pagespeed insights also tends to provide more accurate “real world” user data, so we would always recommend running a test with this as well as Lighthouse. 

Third party tools such as Webpagetest are also useful, providing CLS scores along with a visual page loading process, broken down by the millisecond. 

Check Real User Data  

While lab tests are helpful, you can verify that your optimisations are translating into real user experiences.

Check the “page experience” and “core web vitals” sections of Google Search Console, which will provide you with information on specific URL’s which are flagging with CLS issues. 

Be sure to check results for both Mobile and Desktop versions of your website, as issues can often appear on one but not the other. 

Final thoughts 

To avoid harmful cumulative layout shifts, develop a proactive strategy to ensure that any design changes & new content uploads follow the above steps. 

Thorough testing is crucial to measure improvements from applied fixes. With attention to these areas, you can achieve an excellent CLS score and provide a seamless user experience. 

Add comment