Hot Tip re: Meteor + React + Google Tag Manager

This took some figuring out. I had Meteor + React + Google Tag Manager working fine on my dev system, and even when hosted via Ngrok. But when I pushed it to production – Google Tag Manager reported that the tag wasn’t found. It got even weirder than that. The Google Tag Manager script in the head section – appeared never to have even run. The variable dataLayer was never initialized. I don’t quite understand what caused this yet.

Here’s the script I’m talking about, that Google provides and tells you to put in the head section. I had it in main.html of course.

    <!-- 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-nnnnnnnnn');</script>
    <!-- End Google Tag Manager -->

    <!-- I added this too -- in dev it ran -- in production it never logged to the console -->
    <script async>
        var msg = typeof(dataLayer) == 'undefined' ? 'undefined' : dataLayer;
        console.log('cp #100. dataLayer: ', msg);
    </script>

It seems odd that it never runs. But, once I figured out it wasn’t running, I moved it to a useEffect in my React Router.jsx component – and it worked.

useEffect(() => {
    // Function to load GTM because it DOESN'T WORK WHEN IT'S IN THE HEAD SECTION OF MAIN.HTML
    const loadGTM = () => {
        (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-nnnnnnnnn');
    };

    // Call the function to load GTM
    loadGTM();

    // set up TagManager
    const tagManagerArgs = {
        gtmId: 'GTM-nnnnnnnnn'
    };
    TagManager.initialize(tagManagerArgs);
}, []);
1 Like