Optimize and Google Tag Manager

How to add Optimize to your website when you use Tag Manager.

In order to run Optimize experiments, you need to add the Optimize snippets to your website. The main Optimize snippet is a line of code that’s added to your existing Google Analytics tracking code. This line of code loads the specified Optimize experiment container as a Google Analytics plugin. The page-hiding snippet reduces the risk of page flicker and timeouts on slow connections.

How do you deploy Analytics?

How you deploy Optimize depends on how you deploy Analytics. Choose the option below that best describes your configuration:
 
Most users with a simple Analytics installation, and not using a Tag Management System (TMS) like Google Tag Manager, should use this article for the simplest installation of Optimize.
 
Advanced users who deploy Analytics with a TMS have two options:
 
  1. For the best performance we recommend deploying Optimize directly on the page. Learn more about this option, below.
  2. For greater flexibility, but slightly less performance, you can deploy Optimize via Google Tag Manager. Learn more.
In this article:

Introduction

To run Optimize experiments, you must add a modified version of your Google Analytics tracking code directly to your page. The Optimize plugin is a line of code added to Analytics that loads the specified Optimize container.

When you deploy Analytics tags through Tag Manager, it is still recommended that you install the Analytics tracking code with the Optimize plugin directly on the page (as opposed to deploying Optimize through a tag in GTM). You will modify the code so that it doesn't send any Analytics hits. You do not have to modify your Analytics tags in Tag Manager.

While you can also deploy Optimize directly via Tag Manager, this approach should be used sparingly, as the method documented below will perform better.

Step 1: Modify your Analytics tracking code

To start, create a modified version of your Analytics tracking code to deploy directly on your site. If your Analytics tags in Tag Manager have custom Analytics tracker settings, you must add the same customizations here.

Here’s how to create a modified version of your Analytics tracking code:

1. Copy your existing Analytics tracking code, including any customizations that you’ve made. If your Analytics tags in Tag Manager have custom Analytics tracker settings you must include them in the Analytics create command. For example, the following “create” command enables automatic cookie domain configuration and sets allowLinker to true:

ga('create', 'UA-XXXXXX-X', 'auto', {allowLinker: true});

The following fields must have the same values in both Tag Manager and Analytics:

  'clientId',
  'sampleRate',
  'siteSpeedSampleRate',
  'alwaysSendReferrer',
  'allowAnchor',
  'allowLinker',
  'cookieName',
  'cookieDomain',
  'cookieExpires',
  'cookiePath',
  'legacyCookieDomain',
  'legacyHistoryImport',
  'storeGac'

 

2. Add the Optimize plugin as a new line directly below the Analytics create command above:

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

3. Remove this line if you fire Analytics tags via Tag Manager:

ga('send', 'pageview');

Note: Replace UA-XXXXXXXX-Y with your Analytics tracking ID and replace GTM-XXXXXX with your Optimize container ID.

 

Example: Analytics tracking code with Optimize plugin

The following is an example of the modified Analytics tracking code with Optimize plugin:


<script>
  (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','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-XXXXXXX-Y', 'auto');  // Update tracker settings 
  ga('require', 'GTM-XXXXXX');           // Add this line
                                         // Remove pageview call
  
</script>

Note: Replace UA-XXXXXXXX-Y with your Analytics tracking ID and replace GTM-XXXXXX with your Optimize container ID.

Step 2: Add the page-hiding snippet

We recommend that you also install the page-hiding snippet on your web pages. While it is optional, it significantly reduces the risk of page flicker and helps provide a better experience to users on slow connections. Experiment variants will be shown only when the Optimize container loads within a certain period of time. We’ve designed this snippet to be as performant as possible.

Learn more about the page-hiding snippet.

Example: Page-hiding snippet

The Optimize page-hiding snippet looks like this:


<!-- Page-hiding snippet (recommended)  -->
<style>.async-hide { opacity: 0 !important} </style>
<script>(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date;
h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};
(a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;
})(window,document.documentElement,'async-hide','dataLayer',4000,
{'GTM-XXXXXX':true});</script>

Note: Replace GTM-XXXXXX with your Optimize container ID.

Learn more about customizing the page-hiding snippet, including how to configure the timeout value, in the Optimize Developer Guide.

Step 3: Add the code to your web pages

The final step is to add the modified Analytics tracking code and page-hiding snippet directly on the page. They should be added as high as possible in your page’s <HEAD> tag. The page-hiding snippet should be located above the modified Analytics tracking code. Add the code to all of your web pages or just the pages that you wish to experiment on.

Learn more about the order of the snippets in the tagging best practices section below.

Example: Page-hiding snippet and modified Analytics tracking code

The following is an example of the page-hiding snippet and modified Analytics tracking code with Optimize plugin:

<HTML>
<HEAD>
<!-- Page hiding snippet (recommended)  -->
<style>.async-hide { opacity: 0 !important} </style>
<script>(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date;
h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};
(a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;
})(window,document.documentElement,'async-hide','dataLayer',4000,
{'GTM-XXXXXX':true});</script>
<!-- Modified Analytics tracking code with Optimize plugin -->
    <script>
    (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','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-XXXXXXX-Y', 'auto');  // Update tracker settings 
  ga('require', 'GTM-XXXXXX');           // Add this line
                                         // Remove pageview call
  
</script>

Note: Replace UA-XXXXXXXX-Y with your Analytics tracking ID and replace GTM-XXXXXX with your Optimize container ID.

 

Tagging best practices

Placement of the Optimize code snippets is important. Generally, the order of the tags should be:

  1. Any JavaScript (e.g. jQuery) that you wish to use in Optimize experiments. We recommend you keep these to a minimum
  2. Initialization of any variables needed for targeting (data layer, JavaScript, cookies, etc.)
  3. Page-hiding snippet
  4. Modified Analytics tracking code with Optimize plugin
  5. Tag Manager container snippet
  6. Other JavaScript, trackers, and ad tags

Here are some best practices to keep in mind when adding the code to your web pages:

  1. The page-hiding snippet should be placed immediately before the modified Analytics tracking code (after the <meta charset> declarations).
  2. Move your Google Analytics tracking code up to the <HEAD>, if it's not already there. It should immediately follow the page-hiding snippet, if possible.
  3. The following should come before the modified Analytics tracking code:
    • <meta charset>
    • Data layer initialization
    • Setting cookies
    • Any scripts that you may want to use or that declare JavaScript variables that you wish to use in Optimize experiments. For example, jQuery and JavaScript used to target an Optimize variant
    • Page-hiding snippet
  4. The following should come after the modified Analytics tracking code:
    • Other trackers, analytics tags, ad tags and/or tags deployed by a tag-management system
    • Other scripts that you won’t target Optimize experiments against

You can also target variables that are set after Optimize plugin loads, for example with dynamic pages or web apps, by using Activation Events.

Alternate method: Serve Optimize via Google Tag Manager

While it’s possible to deploy the Optimize plugin via Google Tag Manager, it will often result in significantly increased latency. Learn more about using the native GTM tag type.

Next steps

After you deploy the combined Optimize-Analytics snippet on your web page(s), you’re ready to create your first A/B, redirect or MVT test.

Was this article helpful?
How can we improve it?