How can I improve my CLS score?

There are several techniques that you can use to improve the Cumulative Layout Shift (CLS) score of your website:

  1. Use size attributes for images and video elements: By specifying the width and height of images and videos in your HTML or CSS code, you can ensure that the layout of the page is not affected by the loading of these elements. This can help to prevent layout shifts that may occur when these elements are loaded.
  2. Avoid inserting content above existing content: If you need to insert new content into a page, try to avoid inserting it above existing content. This can cause layout shifts as the page adjusts to the new content. Instead, try to insert new content below existing content or use techniques such as lazy loading to load content as it is needed.
  3. Use font-display: The font-display property allows you to specify how font files should be loaded and displayed on your website. By setting this property to “swap” or “fallback”, you can ensure that the layout of the page is not affected by the loading of fonts.
  4. Defer non-critical resources: If you have resources on your page that are not critical to the initial rendering of the page, such as large JavaScript libraries or third-party widgets, consider deferring their loading until after the main content of the page has been displayed. This can help to reduce layout shifts that may occur as these resources are loaded.

    Use the DOMContentLoaded event: If you have JavaScript that manipulates the layout of your page, consider using the DOMContentLoaded event to trigger this code. This event is fired when the initial HTML of the page has been parsed, which can help to reduce layout shifts caused by JavaScript code that runs as soon as the page loads.

    By following these techniques, you should be able to reduce the layout shifts that occur on your website and improve your CLS score. It’s also a good idea to regularly test your website using tools like Lighthouse or Chrome DevTools to track your CLS score and identify any remaining issues.

Related Questions