- Optimizely Web Experimentation
AngularJS is one of the most popular single-page application (SPA) frameworks in use today. Optimizely Web Experimentation will not work out of the box on a single-page application, but there are some easy steps to follow to make AngularJS work seamlessly. Optimizely Web Experimentation runs during the page load event, which is what you want for a normal web page. When the browser loads the page, Optimizely Web Experimentation runs, evaluates the targeting conditions of each experiment, and executes them if they meet those conditions. For SPAs, there is no page reload when navigating from page to page, so Optimizely Web Experimentation is not executed and does not activate the experiments even if they are configured to run on the current URL.
By default, Optimizely Web Experimentation experiments are executed immediately, and Optimizely Web Experimentation evaluates their targeting conditions when possible when the page loads. Optimizely Web Experimentation has several activation modes.
For AngularJS, switching your experiments to be manually activated makes them run without having to do any additional configuration.
Implementation
To enable Optimizely Web Experimentation to run your experiments on an AngularJS site, copy the following lines of codes to Project JavaScript:
(function() { 'use strict'; // Wait for angularJS to be ready var interval = setInterval(function () { if (window.angular !== undefined && window.angular.element(document.getElementsByTagName('body')).scope() !== undefined) { clearInterval(interval); var scope = window.angular.element(document.getElementsByTagName('body')).scope(); // Listen on new page loaded scope.$on('$viewContentLoaded', function () { // Sometimes $viewContentLoaded is called too early, in that case you can use $locationChangeSuccess // Activate the manually activated experiments window.optimizely.push(["activate"]); // Fake a pageview event. // A pageview event will be sent by default if an experiment is running. // They get de-duplicated server side window.optimizely.push(["trackEvent", document.URL]); }); } }, 500); })();
This code uses an AngularJS listener and the Optimizely Experimentation JavaScript API to activate experiments every time AngularJS loads a new page. Experiments must still meet the URL and audience targeting conditions to be executed. It also fires an Optimizely custom event to register the pageview for every new page so it can be used as a pageview goal in your experiments.
Set up the experiment
You must switch the activation mode of your experiments from Immediate to Manual. Refer to Activate pages to learn how to change the activation mode.
Make sure the URL targeting is set up correctly. You can now start the experiment, and it will activate on your AngularJS page.
Please sign in to leave a comment.