Skip to content

Instantly share code, notes, and snippets.

@klevu

klevu/A-B Testing Logic .js Secret

Last active Apr 22, 2021
Embed
What would you like to do?
RECS A-B Testing
<script type="text/javascript">
/**
* Add this new flag above klevu.interactive().
*
* Set to 'true' to allow GTM to control whether or not
* your Recommendation banners appear. GTM will do this
* by updating the value of another variable:
* klevu_isRecsABTestActiveForCustomer
*
* Set to 'false' for your banners to always appear.
*/
window.klevu_isRecsABTestEnabled = true;
/**
* Modify klevu.interactive to delay the initialisation
* of Klevu Recommendations until the GTM A/B Test has
* determined whether or not they should be displayed.
*/
klevu.interactive(function () {
var options = {
// the powerUp of recsModule has been removed from here
recs: {
apiKey: 'klevu-12345'
}
};
// the powerUp of recsModule is added here instead
if(!klevu.gtm.checkForABTest()){
options.powerUp = {recsModule: true};
}
klevu(options);
});
/**
* Modify your existing klevu.extend to add one more section 'gtm'.
* This will check for the klevu_isRecsABTestEnabled flag mentioned above.
*/
klevu.extend(true, klevu, {
gtm: {
checkForABTest: function () {
if (typeof window.klevu_isRecsABTestEnabled !== "undefined" && window.klevu_isRecsABTestEnabled) {
return true;
}
return false;
}
}
});
/**
* The following should be added as a new section underneath your existing
* klevu.interactive. This new code will power up Klevu Recommendations
* once GTM A/B test determines this customer should see the banners.
*/
klevu.interactive(function () {
if (klevu.gtm.checkForABTest()) {
klevu.coreEvent.build({
name: "gtmCheckForABTest",
fire: function () {
if (typeof window.klevu_isRecsABTestActiveForCustomer !== "undefined") {
return true;
}
return false;
},
maxCount: 100,
delay: 150
});
klevu.coreEvent.attach("gtmCheckForABTest", {
name: "initRecs",
fire: function () {
if (window.klevu_isRecsABTestActiveForCustomer) {
var options = {
powerUp: {
recsModule: true
}
};
klevu(options);
}
}
});
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment