Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Tag Manager script blocks main thread causing low performance

I'm working on improving the performance of a site. After some investigation, I'm focusing on reducing the Total Blocking Time (TBT). Chrome Lighthouse tells me to "Reduce the impact of third-party code Third-party code blocked the main thread for 250 ms". It seems that Google Tag Manager and Google Analytics are blocking the thread for most of the time: enter image description here

Checking the performance tab confirms this too: I have 4 "long-tasks" and 3 out of them are related to Google Tag Manager or Analytics.

The below code shows, how Google Tag Manager is included in the site:

<head>

        <!-- Google Tag Manager -->
        <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
        new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
        j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
        'https://www.googletagmanager.com/gtm.js?id='+i+dl+ '&gtm_auth=XXXXXXXXXXXXX&gtm_preview=env-2&gtm_cookies_win=x';f.parentNode.insertBefore(j,f);
        })(window,document,'script','dataLayer','GTM-XXXXXXX');</script>
        <!-- End Google Tag Manager -->

Is this normal that GTM has 3 tasks and blocks the main thread and causes a high TBT? Am I doing anything wrong? Is there any way to fix this and reduce the TBT while having GTM on the site?

Thanks! W.

like image 250
wanderlusted Avatar asked Dec 18 '25 23:12

wanderlusted


2 Answers

The best solution I've found is partytown, which moves your analytics scripts off the main thread and into a worker

like image 117
Ben McCann Avatar answered Dec 21 '25 11:12

Ben McCann


We solved it in the following way, keep in mind that you will lose the stats of people who spend less than 5 seconds viewing the page.

window.addEventListener('DOMContentLoaded', (event) => {
    window.onload = function() {
        setTimeout(function() {
            (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
            new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
            j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
            'https://www.googletagmanager.com/gtm.js?id='+i+dl+ '&gtm_auth=XXXXXXXXXXXXX&gtm_preview=env-2&gtm_cookies_win=x';f.parentNode.insertBefore(j,f);
            })(window,document,'script','dataLayer','GTM-XXXXXXX');
        }, 5000);
    };
});
like image 22
Kijam Avatar answered Dec 21 '25 11:12

Kijam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!