我们尝试设置google实验来与我们的后端设置一起工作,并发现有API可以让GA知道我们选择通过函数向用户显示的变化:
cxApi.setChosenVariation(chosenVariation, opt_experimentId);
当我访问官方文档:https://developers.google.com/analytics/devguides/collection/gajs/experiments它说:"ga.js是一个遗留库。如果你开始一个新的实现,我们建议你使用这个库的最新版本,analytics.js。对于现有的实现,学习如何从ga.js迁移到analytics.js。"
我们使用的是analytics.js。
这是否意味着ga.js中存在的所有函数都已经在analytics.js中,我们不需要担心使用这个函数?
您可以尝试在https://developers.google.com/analytics/devguides/collection/analyticsjs/experiments上解释的仅支持浏览器的实现。你可以试试gtag.js,而不是ga.js或analytics.js。访问https://developers.google.com/analytics/devguides/collection/gtagjs/migration了解如何从analytics.js迁移到gtag.js。我在下面分享我是如何实现我的实验的代码。记得在Google Analytics中创建实验,你可以在BEHAVIOR> Experiments部分找到它。在下面的代码中,您需要使用自己的实验ID。
<head>
.......................................
.......................................
.......................................
<!-- Load the Content Experiment JavaScript API client for the experiment -->
<script src="//www.google-analytics.com/cx/api.js?experiment=MY_EXPERIMENT_ID"></script>
<script>
// Ask Google Analytics which variation to show the user.
var chosenVariation = cxApi.chooseVariation();
// Define JavaScript for each page variation of this experiment.
// Wait for the DOM to load, then execute the view for the chosen variation.
$(document).ready(function(){
switch (chosenVariation) {
case 0:
// Original: Do nothing. This will render the default HTML.
break;
case 1:
//document.getElementsByClassName('logo_tagline')[0].value = 'I love programming';
$(".logo_tagline:first").text("I love programming");
break;
case 2:
//document.getElementsByClassName('logo_tagline')[0].value = 'Programming is my passion';
$(".logo_tagline:first").text("Programming is my passion");
break;
case 3:
//document.getElementsByClassName('logo_tagline')[0].value = 'I enjoy writing code';
$(".logo_tagline:first").text("I enjoy writing code");
}
});
</script>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-X"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXXXXX-X');
</script>
</head>