Search code examples
javascriptgoogle-analyticsgoogle-tag-managerweb-performancegoogle-optimize

How to fix websites performance after installing google tag manager?


We have google tag manager running on our site. I used to put it as well as some other non urgent scripts inside a javascript "setTimeout" of 3.5 seconds on page load which was a trick I used to give fantastic performance scores on many performance testing tools. However, Google Optimize which is also running would not validate on our site due to the delay in the setTimeout - it only works when it is run on page load without timer delays.

After moving GTM out of the timeout, it has tanked our scores on performance from around 90 to between 20 and 40.

I understand that this likely is due to whats being loaded in GTM but I don't have the ability to not load some of these items in there.

Im wondering if there are other methods to improve page speed performance in a situation like this in which I need GTM and Google optimize loading with the page. The majority of other performance items on our site have already been optimized which is why this drop is so shocking.

Ive attempted to move this GTM tag to the footer as well as set it to load using window.onload but have had no luck. Also, it already is setup using async.

This is what I have it set as now but it is killing performance.

(function () {
            var e = document.createElement('script');
            e.async = true;
            e.src = 'https://www.googletagmanager.com/gtag/js?id=UA-###';
            var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(e, s);

            window.dataLayer = window.dataLayer || [];

            function gtag() {
                dataLayer.push(arguments);
            }

            gtag('js', new Date());

            gtag('config', 'UA-###', {'optimize_id': 'GTM-###'});
        }());

Solution

  • You can use GTM to utilise various triggers on pages, and link different tags to these events. Page view trigger is launched when GTM is initialized. DOM trigger is launched when page is loaded, and Window Loaded trigger is launched when all resources are loaded. You can use these to postpone launch of non-time critical tags, scripts and tools. Further details on these triggers are available in this support article.