Skip to content

Instantly share code, notes, and snippets.

@teimurjan
Last active May 22, 2019 05:12
Show Gist options
  • Save teimurjan/01e07ff0fea14d3e80b558db5c7b06c4 to your computer and use it in GitHub Desktop.
Save teimurjan/01e07ff0fea14d3e80b558db5c7b06c4 to your computer and use it in GitHub Desktop.
Gatsby Google Optimize Utils
const React = require("react");
const config = require("../config");
const createGoogleOptimizeSnippet = experimentsIds => `
gtag('config', '${config.GTM_ID}', {'optimize_id': '${
config.GOOGLE_OPTIMIZE_ID
}'});
${experimentsIds.map(expId => `gtag('set', {'expId': '${expId}'});`)}
window.onload = function(){dataLayer.push({'event': 'optimize.activate'});};
`;
exports.createGoogleOptimizeScript = () => (
<script
key="google_optimize_script"
dangerouslySetInnerHTML={{
__html: createGoogleOptimizeSnippet([config.SIGNUP_EXPERIMENT_ID])
}}
/>
);
const antiFlickerSnippets = {
style: `.async-hide { opacity: 0 !important}`,
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,{'${
config.GOOGLE_OPTIMIZE_ID
}':true});`
};
exports.createAntiFlickeringStyles = () => (
<style
key="anti_flickering_style"
dangerouslySetInnerHTML={{
__html: antiFlickerSnippets.style
}}
/>
);
exports.createAntiFlickeringScript = () => (
<script
key="anti_flickering_script"
dangerouslySetInnerHTML={{
__html: antiFlickerSnippets.script
}}
/>
);

Google Optimize

Redirect tests

In order to test redirecting locally, you have to do the following

  • Create a redirect test in Google Optimize. IMPORTANT! You cannot use localhost as the base URL as Google Optimize cannot recognize non-domain URLs). Pick a domain like http://test.io and add a line 127.0.0.1 test.io to your /etc/hosts.
  • Add YOUR_EXPERIMENT_ID to .env file and to config.
  • Go to googleOptimize.factory.js and add YOUR_EXPERIMENT_ID from config to createGoogleOptimizeScript.
  • Run
    yarn build
    sudo gatsby serve -p 80
    
    and test redirects at the domain you've added(http://test.io).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment