CLS to 0 with 10 lines of code

How I got my Cumulative Layout Shift to 0 with 10 lines of code…

William Belk
2 min readMay 31, 2022

We know Cumulative Layout Shift (CLS) is a ranking factor for Google. CLS measures how much the layout shifts on a web page when loading. CLS falls under the category of ‘page experience’ and is measured in Core Web Vitals.

I ran a bit of an experiment on a marketing site for my new Shopify product reviews app, Rapid Reviews.

I was getting a bad CLS number and my page load was very jumpy. I tried to figure out the most simple way to solve this (with raw javascript), and keep Google’s PageSpeed Insights score happy.

I ended up with the code below—which hides the <body> on load, and adds a very short setTimeout() and css transition to show it. It seems like the entire DOM is already structured with widths and heights computed by the end of the 3ms timeout. Pretty cool.

Please comment if you think this solution is garbage, or great, or someone else already did this way before me. I’m just throwing it out there as it may help some other people think about the problem / solution space.

<style>
body {
opacity: 0.01;
transition: opacity 0.1s ease-out;
}
body.active {
opacity: 1;
}
</style>
<script>
function activateBody () {
var bodyEl = document.querySelector('body')
setTimeout(function(){
bodyEl.classList.add('active')
}, 3)
}
// RUNS ON DOM COMPLETE, NOT PAGE READY
// PAGE READY IS WAY TOO SLOW
if (document.readyState !== 'loading') {
activateBody()
} else {
document.addEventListener('DOMContentLoaded', activateBody)
}
</script>

Results

The Mobile results are largely unchanged, with a 2 point penalty to the score. This may just be natural variance.

The Desktop results are very interesting, with a 13 point improvement!

This seems to suggest that CLS is a much larger page score factor on Desktop than on Mobile. A 13 point swing is pretty wild for such a simple change.

Mobile — BEFORE

Rapid Reviews CLS to 0: Mobile — Before

Mobile—AFTER

Rapid Reviews CLS to 0: Mobile — After

Desktop—BEFORE

Rapid Reviews CLS to 0: Desktop — Before

Desktop—AFTER

Rapid Reviews CLS to 0: Desktop — After

Find me at WilliamBelk.com. Follow me on Twitter.

--

--