google-analyticsgoogle-optimize

Why does Google Optimize not load via Google Analytics 'require'?


I've followed these instructions to load the Google Optimize snippet via Google Analytics: https://support.google.com/optimize/answer/6262084

It basically comes down to one new line in my GA code:

ga('require', 'GTM-S1O2M3E');

The whole GA snippet looks like this (I've added line breaks for readability):

(function (i, s, o, g, r, a, m) {
    i['GoogleAnalyticsObject'] = r;
    i[r] = i[r] || function () {
        (i[r].q = i[r].q || []).push(arguments);
    }, i[r].l = 1 * new Date();
    a = s.createElement(o);
    m = s.getElementsByTagName(o)[0];
    a.async = 1;
    a.src = g;
    m.parentNode.insertBefore(a, m);
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

ga('require', 'GTM-S1O2M3E');
ga('create', 'UA-NNNNNNNN-N', 'auto');
ga('send', 'pageview');

When I run a preview of my Optimize experiment, the Google Optimize Chrome extension complains after a few seconds with this alert:

The Google Optimize snippet for the container with ID GTM-S1O2M3E is not correctly installed on this page.
To preview experiences or debug the container, make sure the Google Optimize snippet is installed on any pages
you want to test.

Inspecting the Network tab in the Developer Tools, I cannot find any request that contains my OPT_CONTAINER_ID - it looks like GA never loads it! Also, checking for the global variable google_optimize returns undefined (I found that here: https://support.google.com/optimize/answer/9059383?hl=en).

BUT when I execute the line ga('require', 'GTM-S1O2M3E'); in the Developer Tools console manually, I see both a new request happening and the google_optimize variable being instantiated!

So WHY does GA not load the Optimize script in the beginning, as it should?


Solution

  • Try reversing the following lines of code

    From:

    ga('require', 'GTM-S1O2M3E');
    ga('create', 'UA-NNNNNNNN-N', 'auto');
    ga('send', 'pageview');
    

    To:

    ga('create', 'UA-NNNNNNNN-N', 'auto');
    ga('require', 'GTM-S1O2M3E');
    ga('send', 'pageview');