Example usage of the JavaScript (Browser) SDK prior to v6
A brief code example of how to use the Optimizely Feature Experimentation JavaScript (Browser) SDK to evaluate feature flags, activate A/B tests, or feature tests.
After installing the JavaScript (Browser) SDK, import the Optimizely library, get your project's datafile, and create a client. Use the client to evaluate flag rules like A/B tests and flag deliveries.
This example walks through the following three key steps:
-
Evaluate a flag with the key
product_sortusing thedecidemethod. This also sends a decision event to Optimizely to record that the user was exposed to the experiment. -
Run code based on the flag result. The SDK evaluates your flag rules and determines which variation the user is in. You can either:
- Check the flag's enabled state and read a configuration variable (
sort_method) to determine which experience the user gets. - Check the flag variation directly and run the corresponding control or treatment code.
- Check the flag's enabled state and read a configuration variable (
-
Track a conversion event called
purchasedto measure the experiment's impact. ThetrackEventmethod ties the purchase back to the A/B test and sends it to Optimizely so it shows up on your results page.
WarningDO NOT use the unpkg CDN and the using HTML script tags example in production environments.
If you rely on unpkg URLs without specifying the package version, your application may unexpectedly break when a new major version of the JavaScript SDK is published to npm, even if you did not explicitly upgrade.
unpkg is a public CDN for open-source packages published to npm. It
- has no uptime guarantees.
- automatically serves the latest version of an npm package when no version is specified in the url, including breaking major version changes.
If you still decide to use unpkg in production, ensure that the version of the SDK is specified in the URL.
import { createInstance } from '@optimizely/optimizely-sdk';
const optimizely = createInstance({
sdkKey: '<YOUR_SDK_KEY>' // Provide the sdkKey of your desired environment here
});
if (optimizely) {
optimizely.onReady().then(({ success, reason }) => {
if (!success) {
throw new Error(reason);
}
const attributes = { logged_in: true };
const user = optimizely.createUserContext('user123', attributes);
if (!user) {
throw new Error('failed to create user context');
}
const decision = user.decide('product_sort');
const variationKey = decision['variationKey'];
if (variationKey === null) {
console.log(' decision error: ', decision['reasons']);
}
const enabled = decision['enabled'];
if (enabled) {
const sortMethod = decision.variables['sort_method'];
// execute code for sort method value
}
if (variationKey === 'control') {
// Execute code for control variation
} else if (variationKey === 'treatment') {
// Execute code for treatment variation
}
// Track an event
user.trackEvent('purchased');
}).catch((err) => {
// handle error
});
} else {
// there was an error creating the instance, handle error
};
<html>
<head>
<title>Hello world</title>
<!-- Install Optimizely SDK -->
<!-- Update VERSION_NUMBER with the version of the JavaScript SDK you want to use -->
<script src="https://unpkg.com/@optimizely/optimizely-sdk@VERSION_NUMBER/dist/optimizely.browser.umd.min.js"></script>
<!-- Add your datafile using your SDK key so you can later instantiate an Optimizely client -->
<script src="https://cdn.optimizely.com/datafiles/<YOUR_SDK_KEY>.json/tag.js"></script>
</head>
<body>
<h1>Hello world</h1>
</body>
<script>
// instantiate an Optimizely client from the datafile
var optimizelyClient = window.optimizelySdk.createInstance({
datafile: window.optimizelyDatafile
});
if (optimizelyClient) {
optimizelyClient.onReady().then(({ success, reason }) => {
if (!success) {
throw new Error(reason);
}
const attributes = { logged_in: true };
const user = optimizelyClient.createUserContext('user123', attributes);
if (!user) {
throw new Error('failed to create user context');
}
const decision = user.decide('product_sort');
const variationKey = decision['variationKey'];
if (variationKey === null) {
console.log(' decision error: ', decision['reasons']);
}
const enabled = decision['enabled'];
if (enabled) {
const sortMethod = decision.variables['sort_method'];
// execute code for sort method value
}
if (variationKey === 'control') {
// Execute code for control variation
} else if (variationKey === 'treatment') {
// Execute code for treatment variation
}
// Track an event
user.trackEvent('purchased');
}).catch((err) => {
// handle error
};
} else {
// there was an error creating the instance, handle error
};
</script>
</html>Updated 8 days ago
