Background styles for perceived performance 🎨

Use simple CSS rules to make your embedded content feel faster

The relatively new Cumulative Layout Shift (CLS) Core Web Vitals metric gives us a way to measure a page's visual stability. In brief, CLS is calculated as the product how much content on the screen is moving, and how far it moves. Lower layout shift improves the user experience by preventing mis-clicks and visual distractions. CLS can be reduced by including size attributes on images and videos to reserve space for the element.

cls
From Google Developers https://web.dev/cls/

What about color shifts? ¶

Color shifts during page load can be almost as jarring as layout shifts. Color shifts can happen as videos, advertisements, and other media load on the page. In the example below, we see a YouTube video being loaded in an iframe over a throttled connection (Fast 3G, 4x CPU throttling).

On /no-background.html there is noticeable empty whitespace reserved for the YouTube player. This is good for preventing layout shifts but draws attention to the lack of content. We see a black rectangle appear when the video loads.

/background.html loads the same video, but the iframe has style background-color: #000; which mimics the background color of the YouTube player. Check out the project on Glitch.

Results ¶

#000 evaluates to the color black. With a black background, the space and primary color for the video player are reserved. While the video takes the same amount of time to load, the page with the black background feels faster because there is no longer a flash when the video player loads—the black background was there all along.

Alternatives ¶

However, each alternative makes an additional request for the image (and certain placeholder images could be more distracting once content loads than using no image at all).

Final considerations ¶

Asset optimization and lazy-loading remain important ways to improve a page's actual performance. Adding a background-color to embedded content can be a simple and effective way to improve perceived performance.

Enjoy what you read? Feel free to share this post!

Published