Search code examples
javascriptgoogle-tag-managerpagespeedgoogle-pagespeedpage-load-time

Avoiding content layout shift with inserting element after onLoad with Google Tag Manager


On a client's site I have an element, which produces CLS, content layout shift. This element is not critical for the site's functioning.

According to Nic Jansma, CLS measuring ends up with onLoad event.

My idea is to remove this element from the source code and load it after onLoad event with Google Tag Manager. Sadly I can't go the usual way, because of the issue nr. 3, according to Simo Ahava's classification.

<script>
    var d1 = document.getElementById('article');
    d1.insertAdjacentHTML('afterend', '<div id="quicknavi-button-container">Content</div>');
</script>

What should I adjust on my javascript? It fires an error I can't interpret:

Cannot read properties of null (reading 'insertAdjacentHTML')


Solution

  • When CLS ends depends on the tool measuring it. For Lighthouse, it "ends" when the tool stops profiling the page (which may be multiple seconds after onload). For the Chrome User Experience Report, CLS is measured up through unload (i.e. the entire page view experience). For most Real User Monitoring (RUM) tools, CLS ends when they send the beacon, which is often at the onload event.

    So it's not that CLS always ends at onload -- it's a cumulative measurement and the value reported depends on the tool you're using or care about.

    The best way to address CLS concerns isn't to play tricks with avoiding the measurement tools (e.g. trying to only load content after onload to avoid detection), but to understand the user experience and address those shifts in the right way. For example, by either pre-allocating vertical "space" for the element, or load it in a way that doesn't shift the content.