Search code examples
google-analyticsgoogle-tag-managergtag.js

Why am I getting gtag is not defined with GTM script


I have an issue that I believe just started happening and we didn't change anything with website that would affect this that I know of. It used to work and I double checked in the Tag manager portal the ID we use is still valid and accurate on https://tagmanager.google.com/....

VM16:1 Uncaught ReferenceError: gtag is not defined at :1:1 at www.googletagmanager.com/gtm.js?id=&l=MaterionData:309:414 at www.googletagmanager.com/gtm.js?id=&l=MaterionData:310:118 at c (www.googletagmanager.com/gtm.js?id=&l=MaterionData:311:160) at qc (www.googletagmanager.com/gtm.js?id=&l=MaterionData:47:19) at e (www.googletagmanager.com/gtm.js?id=&l=MaterionData:151:278) at www.googletagmanager.com/gtm.js?id=&l=MaterionData:31:130 at Array. (www.googletagmanager.com/gtm.js?id=&l=MaterionData:152:370) at Object.execute (www.googletagmanager.com/gtm.js?id=&l=MaterionData:152:110) at ak (www.googletagmanager.com/gtm.js?id=*****&l=MaterionData:152:845)

Here is our server side rendering code

if (Model.CustomDimensionDictionary != null && Model.CustomDimensionDictionary.Count > 0)
{
    <script>
     @foreach (var customDimension in Model.CustomDimensionDictionary)
     {
         @:MaterionData = [{'dimension3': '@customDimension.Value'}];
     }
    </script>
}

<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; f.parentNode.insertBefore(j, f);
    })(window, document, 'script', 'MaterionData', '@Model.MainSiteNode.GoogleAnalyticsPropertyId');

</script>
<!-- End Google Tag Manager -->
<noscript>
    <iframe src="https://www.googletagmanager.com/ns.html?id=*******"
            height="0" width="0" style="display:none;visibility:hidden"></iframe>
</noscript>
<!-- End Google Tag Manager (noscript) -->

Solution

  • I looked at the link BNazaruk sent and added these two lines just before the </script> tag in header and now it works:

    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}