Google Tag Manager script blocks main thread causing low performance

wan*_*ted 12 javascript performance google-tag-manager

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: 在此输入图像描述

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 -->
Run Code Online (Sandbox Code Playgroud)

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.

Ben*_*ann 1

我发现的最好的解决方案是partytown,它将您的分析脚本从主线程移到工作线程中

  • 它消除了来自该脚本的阻塞时间。仅通过将 Google Analytics 从主线程中移出,我的 Lighthouse 分数就提高了约 10 分 (2认同)