Optimizing Web Performance Metrics: Navigating Practical Solutions and Best Practices
In the pursuit of delivering high-quality user experiences and achieving impressive web performance scores, developers often encounter challenges that require creative solutions. One common metric that can be particularly tricky to optimize is Cumulative Layout Shift (CLS), part of Googleโs Core Web Vitals, which measures visual stability during page load.
Recently, I worked on a small website projectโtipping-expert.comโand aimed to improve its Lighthouse performance scores, including CLS. While enhancing metrics is beneficial, sometimes the path involves nuanced decision-making, especially when dealing with dynamic content loading.
A specific challenge arose with CLS on mobile devices. The website has a simple layout structure:
“`html
“`
The core issue was that, during initial load, the React application fetches data asynchronously from an API. Consequently, the <div class="app-body">
remained mostly empty initially, causing the footer to appear in the viewport prematurely, which inflated the CLS score.
The ‘Hack’ Solution
To mitigate the layout shift, I temporarily added a div
with a minimum height of 90 viewport height units (90vh
) inside .app-body
whenever it lacked content. Essentially, this kept the layout stable until real content loaded. Itโs a quick fix that improved the CLS metric, but it felt somewhat hackishโakin to jumping through hoops rather than adopting a systemic solution.
Reflections and Best Practices
While such quick fixes can be tempting, especially for small projects or prototypes, it’s worth considering more sustainable strategies:
-
Prioritize Skeleton Screens or Placeholders: Instead of adding arbitrary heights, use skeleton screens that resemble the eventual content. This provides users with visual cues that content is loading, improving perceived performance and stability.
-
Pre-allocate Space Based on Estimated Content Size: If possible, determine the size of dynamic elements beforehand and reserve space accordingly. This reduces unexpected shifts when data arrives.
-
Optimize Data Fetching and Rendering Timing: Delay rendering of critical layout components until data is available, or progressively render parts of the content as data loads.
-
Leverage CSS and React Features: Use CSS aspect-ratio properties or other techniques to reserve space, and ensure React components do not cause layout reflows after initial render.
Conclusion
In web