This solution works very well for me. The benefits are:
- no node.js required
- no changes to site needed - site remains fully cacheable
- Google Multi-Armed-Bandit approach used, no patch
- easily maintainable
Javascript Module providing all functionality for executing multiple Google Experiments:
var runExperiment = (function(jQ) {
var apiUrl = '/ga-experiments-api.php?preview=true&experimentId=',
experimentId,
variations;
var chooseAndApplyNewVariation = function() {
if (typeof jQ !== 'undefined') {
jQ.ajax({
type: 'get',
url: apiUrl + experimentId,
success: function(data, status){
var choosenVariation = data.choosenVariation;
if (typeof choosenVariation !== 'undefined' && choosenVariation >= 0) {
cxApi.setChosenVariation(choosenVariation, experimentId);
applyVariation(choosenVariation);
}
}
});
}
};
var applyVariation = function(chosenVariation) {
var variationFunction = (typeof variations[chosenVariation] === 'function') ? variations[chosenVariation] : false;
if (variationFunction) {
variationFunction.apply();
sentGaEvent();
console.log(experimentId, chosenVariation);
}
};
var sentGaEvent = function() {
if (typeof ga !== 'undefined') {
ga('send', 'event', 'experiment', 'view');
}
};
return function(experiment) {
experimentId = experiment.id;
variations = experiment.variations;
if (typeof cxApi !== 'undefined') {
var chosenVariation = cxApi.getChosenVariation(experimentId);
if (chosenVariation >= 0) {
applyVariation(chosenVariation);
} else {
chooseAndApplyNewVariation();
}
}
};
})(jQuery);
Javascript Snippet for running single experiment - can be integrated multiple times on page:
(function(jQ) {
var experiment = {
'id': 'RHwa-te2T_WnsuZ_L_VQBw',
'variations': [
function() {},
function() {
jQ('#nav #menu-item-2000927 a').text('Shop + Abo');
}]
};
runExperiment(experiment);
}(jQuery));
PHP (API) for generating new variations through Google's API, I used this class:
https://github.com/thomasbachem/php-gacx
<?php
use UnitedPrototype\GoogleAnalytics;
require_once dirname(__FILE__) . '/libs/googleAnalytics/Experiment.php';
$experimentId = (!empty($_GET['experimentId'])) ? $_GET['experimentId'] : null;
$returnData = array(
'experimentId' => $experimentId,
);
try {
$experiment = new GoogleAnalytics\Experiment($experimentId);
$variation = $experiment->chooseNewVariation();
if (is_integer($variation)) {
$returnData['success'] = true;
$returnData['choosenVariation'] = $variation;
}
} catch (Exception $exception) {
$returnData['success'] = false;
$returnData['error'] = $exception;
}
header('Content-Type: application/json');
echo json_encode($returnData);