Search code examples
javascripthtmlgoogle-tag-managerhead

Defer attribute for the Google Tag Manager


I want to set the defer attribute for the GTM tag and it works well. But, my GTM contains another 10 scripts. The j.defer = true does not affect those scripts. How can I make those script attribute as defer instead of async? (can refer to this image)

Script for GTM

<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.defer = true;
        j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
        f.parentNode.insertBefore(j, f);
    })(window, document, 'script', 'dataLayer', 'XXX-XXXXXXX');
</script>

Solution

  • GTM adds scripts through user-defined logic in tags. You could get access to your GTM account, find tags that load scripts and do exactly the same to them. But it makes no sense since GTM is already deferred, so any scripts it adds to the DOM will effectively be deferred even if not explicitly deferred.

    On the other hand, Unless your GTM container contains mountains of logic, defer should not differ from async in any measurable way, but it may harm the data that GTM collects.

    Say, in case the page loads longer, and the user doesn't wanna wait and just quit, you will not know about that bounced user since GTM is deferred. I'm sure there are more edge cases in events timing in case you use datalayer or if GTM relies on other event listeners that could fire before the page is done loading.