Dev GuideAPI Reference
Dev GuideAPI ReferenceUser GuideProduct feedbackGitHubNuGetDev CommunitySubmit a ticketLog In

Dynamic websites

This topic describes Optimizely's support of single-page applications.

Optimizely Web Experimentation offers a variety of options for supporting single-page applications and other dynamic websites. Different options may be preferable depending on your web application's architecture. Before reading further, we recommend reviewing this article on Support for dynamic websites: Use Optimizely Web Experimentation on single page applications to become familiar with the relevant Optimizely concepts.

Page Activation

Begin by configuring pages to reflect the logical views or components of your application. Pages are the where of Optimizely Web Experimentation. They're sections of your site where you will modify the experience and track behavior. On a non-dynamic website, a page logically maps to a document. On a dynamic website or single-page application, a page should correspond to a section of your site that a visitor would consider a distinct experience.

You can use activation triggers and conditions to indicate when your views are active and need to be optimized. Triggers indicate when a page's conditions should be checked, and conditions determine whether the page should indeed be activated. A page's conditions are checked each time its trigger fires.

Only one "instance" of a page can be active at a time. If you'd like to activate a page multiple times in a given context, then you'll need to deactivate it before activating it again.

Triggers

Triggers indicate when a page's conditions should be checked. There are six trigger options, explained below:

Immediate

The Immediate trigger fires when the Optimizely snippet activates. This is the default trigger.

URL Change

The URL Change trigger fires every time the URL changes, even if only the query string or hash has changed. This trigger also fires when the Optimizely snippet activates, for example, upon initial page load. It is important to note that Optimizely Web Experimentation uses a runtime patch of the History API to detect when the URL changes and fire the trigger. This activation trigger only works if the snippet includes Support for Dynamic Websites.

DOM Change

The DOM Change trigger fires every time the DOM changes. This trigger also fires when the Optimizely snippet activates, for example, upon initial page load. Optimizely Web Experimentation uses a MutationObserver to detect when an element is inserted, removed, or modified. This activation trigger only works if the snippet includes Support for Dynamic Websites.

Callback

To perform a Callback trigger, you provide JavaScript that invokes a callback function when you're ready for the trigger to fire. Your JavaScript will often run before DOM is ready, so you might want to use Optimizely Web Experimentation's utility APIs to defer the callback until the relevant part of DOM is available for modification.

Your JavaScript runs unconditionally before the Page's conditions are checked. If you don't want code to be evaluated every time the snippet activates, you must wrap that code in an if statement that checks the URL or other conditions manually.

📘

Note

If you want to use jQuery in your JavaScript, remember to use Optimizely Web Experimentation's jQuery API: var $ = window.optimizely.get('jquery');

Parameters

  • activate (function) A callback function that fires the trigger when called.
    • isActive (Boolean) Optional parameter to the callback function. If false, the page will be deactivated instead of activated, with no regard for its conditions.
  • options (object):
    • pageId (string) The page ID.
    • isActive (Boolean) Returns true if the page is already active.

Usage

// Poor usage.
function trigger(activate, options) {
  if (/* SOME CONDITION */) {
    document.querySelector('button').addEventListener('click', activate);
  }
}

// Better usage.
function trigger(activate, options) {
  var utils = window.optimizely.get('utils');

  utils.waitForElement('button').then(function(buttonElement) {
    buttonElement.addEventListener('click', activate);
  });
}

// Best usage.
function trigger(activate, options) {
  var utils = window.optimizely.get('utils');

  if (window.location.href.indexOf(/* Some URL */) !== -1) {
    utils.waitForElement('button').then(function(buttonElement) {
      buttonElement.addEventListener('click', function() {
        options.isActive && activate({isActive: false});
        activate();
      });
    });
  }
}

In the "best usage" example above, you'll see that we first check the options.isActive Boolean to determine if the page is already active in the given context, then we explicitly deactivate the page with the optional isActive parameter should options.isActive return true. This usage allows you to reactivate this page as many times as needed when a user clicks on the button element. For more usage examples, please see the code samples section.

Polling

This trigger polls every 50 milliseconds for a JavaScript predicate to return true. The JavaScript function must always return a Boolean value.

Polling for a specific element is a common use case. The trigger will stop polling two seconds after DOM is ready, so for views that may take longer than two seconds to load, consider the DOM Change trigger or Callback trigger instead.

Usage

function pollingPredicate() {
  return document.querySelectorAll("div.btn-green").length > 0;
}

Manual

The Manual trigger fires when a page is pushed using the manual activation API.

📘

Note

You must deactivate the page before being able to reactivate it. See Usage below for code on how to deactivate a page.

Parameters

  • type: "page"
  • pageName (string): The "API name" for a page created in Optimizely, e.g., product_detail. Choose the "manual activation" option in page creation to see or change this name.
  • tags (object): A single-level JSON object with metadata about the content on the page, e.g., the product being purchased.
  • isActive (Boolean): Optional parameter. If false, the page will be deactivated instead of activated, with no regard for its conditions.

Usage

window.optimizely = window.optimizely || [];

// Basic Page activation. `isActive` param is not necessary.
window.optimizely.push({
  type: "page",
  pageName: "checkout_stage_1"
});

// Basic Page deactivation. Must be done to reactivate "checkout_stage_1" again.
window.optimizely.push({
  type: "page",
  pageName: "checkout_stage_1",
  isActive: false
});

// Page activation with tags
window.optimizely.push({
  type: "page",
  pageName: "product_detail",
  tags: {
    category: "Kitchen",
    subcategory: "Blenders",
    price: 64999,
    sku: "113757"
  }
});

Conditions

When a page's trigger has fired, the page's conditions determine whether the page should actually be activated. The page activates if all conditions pass or if there are no conditions to check at all.

URL Match

Determines whether the visitor's URL matches a given rule. This is the default condition.

Element is Present

Determines whether a particular element exists in the DOM. We do this by calling document.querySelectorAll() on the provided CSS Selector.

JavaScript Condition

Determines whether a JavaScript predicate returns true.

Usage

function conditionFn() {
  return dataLayer.pageType === "category";
}

Optimizely desktop application

The Optimizely Web Experimentation Desktop App is an Optimizely application that runs natively on your computer (Windows, macOS, or Linux) and lets you connect to the Optimizely Web Experimentation application without using a browser. This can make editing experiments and campaigns quicker, less error-prone, and easier for single-page applications.

If your team is interested in using the Desktop Application, you can learn more in our article on how to Install the Optimizely Web Experimentation Desktop App.

Optimizely Feature Experimentation SDKs

The Optimizely Feature Experimentation offering is also capable of working on single-page applications. See Optimizely Feature Experimentation.