The JavaScript variant type in Compose serves as a dynamic tool, offering a flexible approach for implementing subtle changes when A/B testing. This article delves into the versatility of the JavaScript variant type, showcasing its ability to modify styles or alter copy. Through real examples, we explore how to leverage the JavaScript variant to enact changes on a site. Understanding and using this variant type will open the door to endless experimentation.
When using the JavaScript variant type, it is important that the code is executed immediately when the variant is triggered. To make sure of this, we are using an Immediately-Invoked Function Expression (IIFE). The general pattern of this is:
(() => {
// your code
})();
Button copy example
This variant type is generally used for testing specific element changes on a page. For example, changing the copy on a button might use the following code:
(() => {
const callback = () => {
// DOM Updates Here
const button = document.getElementById("my-button");
button.textContent = "Shop Now!";
}
if (document.readyState === 'loading') {
document.addEventListener('readystatechange', () = {
if (document.readyState === 'interactive') callback();
})
} else {
callback()
}
})();
The Document Object Model defines the structure of any web page and we can use JavaScript to update it dynamically. This code stores the DOM updates in a callback function.
It then uses document.readyState
to determine if the page is loading. This will evaluate to true when the snippet is loaded into an active test. It can now use readystatechange
to listen for when the page's DOM elements are available via the interactive
state and trigger the callback function. This method reduces the chances of users seeing the content change (flash of original content).
document.readyState
will evaluate to false when you are testing your snippets in your experiment preview, since snippets will always load after the page loads in this setting. You can learn more experiment preview and a live tests here.
Button styling example
Another example is changing the style of a button with the following code:
(() => {
const style = document.createElement('style')
style.textContent = `
#my-button {
background-color: forestgreen;
}
`
document.head.append(style)
})();
In this code, document.createElement('style')
is creating a new <style> element. Then we specify with CSS that we want the element with the ID 'my-button' to have the background color of forestgreen. Then we append that style tag to the <head> so that our specified styles are shown on the page.
This method of directly modifying the document is preferred, as it avoids waiting for the DOM to update your content and potentially creating a flash of original content
As you can see, the JavaScript variant type plays a pivotal role in A/B testing. We hope this helps create meaningful experiments that allow you to elevate the user experience and maximize conversions.