Note: Turn off any ad-blockers! Ad-blockers can prevent this demo from working.
- Create an Optimizely Account
- Open up a blank codepen
- Create a static site by pasting in the following html:
<html>
<head>
</head>
<body>
<h1>Hello World</h1>
<p id="subtitle">This is a subtitle</p>
</body>
</html>
- Install the Optimizely SDK via the html script tag. This makes the SDK available at
window.optimizelySdk
:
<script src="https://unpkg.com/@optimizely/optimizely-sdk@3.5/dist/optimizely.browser.umd.min.js"></script>
- Install the datafile for your project using the html script tag, replacing
Your_SDK_Key
with your SDK key from the Optimizely Application. This makes the SDK available atwindow.optimizelyDatafile
:
<script src="https://cdn.optimizely.com/datafiles/<Your_SDK_KEY>.json/tag.js"></script>
- In a script tag at the bottom of the html, initialize the SDK:
<script>
var optimizelyClientInstance = window.optimizelySdk.createInstance({
datafile: window.optimizelyDatafile,
});
</script>
- Create a feature flag named
hello_world
in the Optimizely UI. - Implement the
hello_world
feature flag:
var userId = 'user123';
var enabled = optimizelyClientInstance.isFeatureEnabled('hello_world', userId);
if (enabled) {
document.querySelector("#subtitle").innerText = "Feature flag is ON!"
} else {
document.querySelector("#subtitle").innerText = "Feature flag is off"
}
- Define a function to get or generate userIds and replace
user123
withgetOrGenerateUserId()
:
function getOrGenerateUserId() {
var userId;
try {
var storageKey = 'optimizely-userId'
userId = window.localStorage.getItem(storageKey);
if (!userId) {
userId = String(Math.random());
localStorage.setItem(storageKey, userId);
}
} catch {
console.warn('[OPTIMIZELY] LocalStorage not available to store userId. Generating random userId each page load');
userId = String(Math.random());
}
return userId;
}
var userId = getOrGenerateUserId();
- Profit 🎉