Search code examples
javascriptphpgoogle-analyticsmagento2google-tag-manager

Google Tag Manager js library sometimes loading sometimes not


We are using Magento 2 CMS and we add a proper script like this -

<!-- 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;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XYZ');</script>
<!-- End Google Tag Manager -->

But it is loading sometimes and sometimes not.

When we checked in the view page source then found that the j.src value shows nothing.

Does anyone know how to resolve this or How can we fix this?


Solution

  • Don't check j.src. You're outside of that function.

    Instead, check the script in DOM and its fetching in Network. Or even just it's JS presence via the dataLayer changes it makes when it loads.