Reduce the impact of third-party code - Google Tag Manager - Analytics

In this post, I describe how to reduce the impact of third-pary code such as Google Tag Manager (gtag) and Google Analytics.

Screenshot of "Reduce the impact of third-party code" diagnostic for Google Tag Manager

This can lead to a longer Largest Contentful Paint (LCP) which can cause Google Search Console Core Web Vitals to report "LCP issue: longer than 2.5s" and URLs as either "poor" or "need improvement".


Cause

The "reduce the impact of third-pary code" message can appear when you run PageSpeed Insights or Lighthouse within Google Chrome on a page which includes the Google Tag (gtag.js).  I found that my performance score would still be negatively impacted even if I used async or defer in the script tag which loaded the Google Tag.

Screenshot showing PageSpeed Insights performance score needs improvement

I tested removing the Google Tag completely and my score improved to 100 so I knew the Google Tag was the cause.


Resolution

To resolve the issue, I set a timeout then loaded the Google Tag Manager after the timeout, in this case 3,000 milliseconds later:

window.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; f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'GTM-123456789');
}, 3000);


(Note: Delaying the Google Tag will mean that data is sent to Google later in the page load and will not be sent if the user leaves the site before script has finished executing.)

This dramatically improved the performance score for my page:

Screenshot showing PageSpeed Insights performance score good

Comments

Popular posts from this blog

LG TV This app will now restart to free up more memory

LG TV Clear All Browsing History Data

LG TV turn off Quick Start in settings