Google Optimize with a custom datalayer
Google Optimize is a relatively new A/B testing framework that’s designed to integrate well with Google’s Universal Analytics and Tag Manager products. If you’re using Tag Manager and have a custom-named data layer, you might run into some installation errors.
If you don't know if your GTM data layer has been renamed from the default "dataLayer", look at the trailing end of the GTM snippet on your page. If the third argument to the tracker is something besides "dataLayer", e.g. "myCustomLayer":
JavaScript
window, document, "script", "myCustomLayer", "GTM-XXXX";
then read on. Otherwise you're using the default data layer, and probably won't run into the issue described in this post.
Optimize is installed as a plugin for Universal Analytics. You can configure Tag Manager to inject it along with your existing tags, but Google recommends against that for best performance:
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). [...] While you can also deploy Optimize directly via Tag Manager, this approach should be used sparingly as [this method] will perform better.
Instead, per Google's instructions you have to include a standard Universal Analytics snippet in the <head>
of your page(s), but replace the “pageview” call with “require”.
Here’s where it gets tricky. The Optimize plugin injects a secondary Tag Manager container on your page. That container doesn’t know about your renamed data layer - and will show an error in your Optimize dashboard. The error indicates a problem with a renamed or reinitialized data layer.
To fix it, Universal Analytics plugin syntax allows you to pass parameters after the plugin name. If your modified Universal Analytics snippet looks like:
JavaScript
// last argument is UA config that should match GTM pageview tag config
ga('create', 'UA-XXXXXX-X', 'auto', { siteSpeedSampleRate: 50, ... }); // last argument is optional
ga('require', 'GTM-XXXXXX');
Modify the last line to add “{ dataLayer: ‘myCustomLayer’ }” after the Optimize container ID:
ga("require", "GTM-XXXXXX", { dataLayer: "myCustomLayer" });
Now when Optimize's container loads, it's able to share information with the Tag Manager container loaded on the page. If all goes well this should fix your Optimize installation error.