Search code examples
javascriptjquerygoogle-analyticsgoogle-tag-manageruniversal-analytics

GTM Google Analytics Custom Dimension Variable Only Firing Some of the Time


I have setup a custom dimension using a custom variable in GTM. However, when I review google analytics reporting I see that the dimension is recorded only about 75% of the time. The same page will track 3/4 of the pageviews with the dimension while the other 25% of the views do not record the dimension. Please see the below code, this is the custom variable I create in javascript, then the following screenshots show how I create the custom variable and create a custom dimension. Is there a reason why this would be happening?

My guess is that maybe the pull page isn't being loaded before I create the javascript variable (the variable code is actually toward the bottom of the page). Or maybe some other javascript on my page is causing the rest of the javascript to fail (I haven't been able to recreate this, but maybe on older browsers or mobile devices). If either of these two scenarios are likely the case then what do I do to fix the problem? Is there a better approach that is more likely to not fail?

<script>
    // For GA
    var ArticleID = 624;
</script>

Custom GTM Variable

Custom Dimension


Solution

  • Based on your setup, it is very likely, that a race condition is present, and the Google Tag Manager (GTM) scripts run earlier compared to your script, that sets the variable. As a result, GTM will not find your variable, and passes undefined value to Google Analytics tracker, which is not sent to Google Analytics itself.

    One of the solutions for this problem is to push this variable into Google Tag Manager's datalayer before the GTM initialization. As a result, the value will be present at the moment GTM initializes, which actually triggers the pageview event.

    So your code will become this:

    <script>
      dataLayer = [{
        'ArticleID': 624
      }];
    </script>
    <!-- Google Tag Manager -->
    ...
    <!-- End Google Tag Manager -->
    

    For further reference about datalayer, you can check out this developer guide.

    Within GTM, you need to replace your JavaScript variable to a dataLayer variable, where the Data Layer Variable Name will be ArticleID.