Returns a utils object that includes useful functions for developing experiences.
Optimizely Web Experimentation uses some common functions to deliver experiences. You can also use those functions to write your own custom experiences.
Syntax
utils = window["optimizely"].get("utils");
Parameters
| Parameter and Type | Child Attribute | Description |
|---|---|---|
| utils string | N/A | The argument indicating to get the utils object. Required. |
Return value
| Parameter and type | Child attribute | Description |
|---|---|---|
| UtilsObject | N/A | The utils object that contains a number of useful functions for developing experiences. |
| observeSelector function[observeSelector] | Child attribute of type UtilsObject. | Run a callback whenever an element changes. |
| poll function[poll] | Child attribute of type UtilsObject. | A setInterval wrapper. |
| waitUntil function[waitUntil] | Child attribute of type UtilsObject. | Wait until the provided function returns true. |
| waitForElement function[waitForElement] | Child attribute of type UtilsObject. | Returns a Promise that is resolved with the first HTMLDomElement that matches the supplied selector. |
| onUrlChange function[onUrlChange] | Child attribute of type UtilsObject. | Run a callback whenever the URL of the current page changes. |
| persistHtml function[persistHtml] | Child attribute of type UtilsObject. | Injects HTML onto the page and re-injects the HTML if it is ever removed. |
Example call
utils = window["optimizely"].get("utils");Example return value
utils.waitForElement(selector);
utils.observeSelector(selector, callback, options);
utils.poll(callback, delay);
utils.waitUntil(conditionFn);
utils.onUrlChange(callback);
utils.persistHtml(html, selector, position);waitForElement()
Returns a Promise that is resolved with the first HTMLDomElement that matches the supplied selector. This is commonly used to make adjustments to the element that you are waiting for when the promise is fulfilled.
Syntax
utils.waitForElement(selector);
Parameters
| Parameter and Type | Child Attribute | Description |
|---|---|---|
| selector string | N/A | A CSS selector indicating the element to wait for. Required. |
Return value
| Parameter and type | Child attribute | Description |
|---|---|---|
| Promise | N/A | An ES6-style Promise that is resolved with the matching element. |
Example call
utils.waitForElement("h2");Examples
Change the color of an element
Wait for an element to be loaded on the dom and change the color as soon as it has become available.
Example code for changing the color of an element
// Retrieve the utils library
var utils = window["optimizely"].get('utils');
// Wait for the footer element to appear in the DOM, then change the color
utils.waitForElement('.footer').then(function(footerElement) {
footerElement.style.color = 'black';
});observeSelector()
Run a callback whenever an element changes. This utility provides a subset of the functionality of a MutationObserver, letting you run a function whenever a DOM selector changes. Given a CSS selector and a callback, this function invokes the supplied callback whenever a new element appears in the DOM matching the supplied selector.
Syntax
utils.observeSelector(selector, callback, options);
Parameters
| Parameter and type | Child attribute | Description |
|---|---|---|
| selector string | N/A | A CSS selector indicating the element to wait for. Required. |
| callback function | N/A | The function that will be executed when the element indicated by the selector changes. The first argument is the exact element that changed. Required. |
| options ObserverOptions | N/A | Timing configuration options. Required. |
| timeout integer or null | Child attribute of type ObserverOptions. | Number of milliseconds or null. Default to null (for example, no timeout). |
| once Boolean | Child attribute of type ObserverOptions. | Only invoke the callback on the first match. |
| onTimeout function | Child attribute of type ObserverOptions. | If timeout is specified and no elements match, execute timeout callback. |
Return value
| Parameter and type | Child attribute | Description |
|---|---|---|
| function | N/A | A function that can be executed to unobserve selector. |
Example call
utils.observeSelector(".productPrice", function(priceElement) {
priceElement.style.fontSize = '30px';
priceElement.style.color = 'red';
}, {
"timeout": 6000,
"once": true,
"onTimeout": function() {
console.log("Stopped observing");
}
});poll()
A setInterval wrapper. The poll function is a convenient wrapper around the setInterval function.
Syntax
utils.poll(callback, delay);
Parameters and Types
| Parameter and type | Child attribute | Description |
|---|---|---|
| callback function | N/A | Function to be executed on the interval specified by delay. Required. |
| delay integer | N/A | Milliseconds to wait in between each callback invocation. Required. |
Return value
| Parameter and Type | Child Attribute | Description |
|---|---|---|
| function | N/A | Returns a function that cancels the polling. |
Example call
var utils = window["optimizely"].get("utils");
var cancelPolling = utils.poll(function() {
timeRemaining = timeRemaining - 1000;
// Update message based on how much time is remaining
if (timeRemaining > 0) {
var date = new Date(timeRemaining);
headerElement.innerHTML = 'You have ' + date.getMinutes() + ':' + date.getSeconds() + ' before your reservation expires.';
} else {
headerElement.innerHTML = 'Your reservation has expired';
cancelPolling();
}
}, 1000);waitUntil()
Wait until the provided function returns true. This utility accepts a function that returns a Boolean value and returns a Promise that resolves when the supplied function returns true.
Syntax
utils.waitUntil(conditionFunction);
Parameters
| Parameter and Type | Child Attribute | Description |
|---|---|---|
| conditionFunction function | N/A | A function that executes synchronously and returns a truthy value when the condition is met. Required. |
Return value
| Parameter and type | Child attribute | Description |
|---|---|---|
| Promise | N/A | An ES6-style Promise that is resolved with the matching element. |
Example call
utils.waitUntil(function() {
var productsShownOnThePage = document.querySelectorAll('.product-listing');
return productsShownOnThePage && productsShownOnThePage.length > 200;
});onUrlChange()
Runs a callback whenever the current URL changes. This utility provides a subset of the functionality of an Event Listener, letting you run a function whenever the current URL changes. This is useful for re-applying changes on a dynamic website where the page does not fully reload during page navigation.
Syntax
utils.onUrlChange(callback);
Parameters
| Parameter and Type | Child Attribute | Description |
|---|---|---|
| callback function | N/A | The function that executes when the URL loaded in the browser change (without a full page reload). Required. |
Return value
| Parameter and type | Child attribute | Description |
|---|---|---|
| Promise | N/A | A function that can be executed to stop the observer from watching for URL changes. |
Example call
utils.onUrlChange(function() {
// Ensure navigation bar stays blue during page navigation
document.querySelectorAll('.nav').style.color = 'blue';
});persistHtml()
Persist a block of HTML on the page. This utility provides a subset of the functionality of a MutationObserver, letting you re-insert and persist HTML onto a page if it is removed. Given a CSS selector and position, this function places the supplied HTML at the position specified around the element in the DOM matching the supplied selector. This is useful for persisting HTML changes on a dynamic website that may remove or 're-hydrate' during page navigation.
Syntax
utils.persistHtml(html, selector, placement);
Parameters
| Parameter and type | Child attribute | Description |
|---|---|---|
| html string | N/A | A string representation of HTML code to be added to and persisted on the page. Required. |
| selector string | N/A | A CSS selector indicating the element the HTML should be inserted around. Required. |
| placement string | N/A | The position around the selector to insert the html. Accepted values are before, after, afterbegin, beforeend Default value is before. |
Return value
| Parameter and type | Child attribute | Description |
|---|---|---|
| Promise | N/A | A function that removes the HTML from the page and stops further injection. |
Example call
// Insert and persist a butter bar before the .nav element
const butterBarHtml = `<div class='butterBar'>This is a notification </div>`
utils.persistHtml(butterBarHtml, '.nav', 'before');Examples
Warn after scrolling
Show the visitor an alert after the visitor has scrolled a significant distance down the page.
// Retrieve the utils library
var utils = window["optimizely"].get('utils');
// We have infinite scroll enabled on the site. Wait until more than 200 products have been shown
// to prompt the user to try out our filter by color feature
utils.waitUntil(function() {
var productsShownOnThePage = document.querySelectorAll('.product-listing');
return productsShownOnThePage && productsShownOnThePage.length > 200;
}).then(function() {
alert('Not finding what you are looking for? Try narrowing down your search using our new filter by color feature');
});For usage patterns that combine utils.waitUntil and utils.waitForElement with page activation, see Use utility functions on dynamic pages.
