An evaluator is custom JavaScript code that runs on the page and returns a value based on data that exists on the page. You can create evaluators to use for:
- Custom targeting conditions: For example, if a user's age exists on your data layer, an evaluator can return this information so that you can target experiences based on the user's age.
- Variable values in templates: For example, if a user's name exists on the page, an evaluator can return the name and use it in a template. This lets you render the name in a variation and create a more personalized user experience.
- Real-time values in custom filtering rules: For example, an evaluator can return the difference between the current cart value and the free-shipping threshold, and request products with a higher price than the evaluator value.
The code is run only when an experience using the evaluator is loaded onto a page. Usually, this happens during the pageload, unless an action delay is applied using triggers. Evaluators have a timeout of 4 seconds, and return as false if the timeout is reached before a result is returned.
Creating an evaluator for websites
- Go to Assets › Evaluators and click Add New.
- Enter a name and notes (optional).
- Define the value type and expected values. These will affect how conditions built on the evaluator will behave:
- Value type: Specify String or Number. If you select Number, the targeting conditions will enable you to specify greater than or less than values. If you select String, you can only target based on values that contain the string.
- Expected values (optional): This limits the available values when using the evaluator as a targeting condition. The specified values are added in a dropdown menu. For example, if your evaluator checks whether the user is logged in or not, you can set expected values to True or False.
- Use the preview to review how the targeting condition will look and behave.
- Click Next, and write your JavaScript code in the editor. See the Writing Evaluator Code section for more information.
- Click Save. Creating, editing, and deleting evaluators can take up to 5 minutes to take effect.
Notes:
- Evaluators can contain up to 5,000 characters.
- In mobile sites using the SDK, use the API Reference for iOS or API Reference for Android to add evaluators directly into your app.
- Mobile SDK end-of-life has been announced and is scheduled for the end of 2023, in favor of updated and more streamlined app personalization using server-side APIs.
Writing evaluator code
Evaluator code is JavaScript code that returns a value. It can be simple code that fetches a text from an element on the page, or it can be code that takes any element on the page, manipulates it, and returns a result.
There are two types of evaluators:
- Regular evaluator: Runs on the page immediately; used when there is nothing asynchronous in the process of getting a result.
- Async evaluator: Depends on another process that has to run on the page to provide a result, such as a DOM element that appears after the page loads.
To avoid cases where an evaluator fails to return a value, or returns null because something does not yet exist on the page, we recommend using a JavaScript promise. This ensures that the targeting conditions evaluation waits until the evaluator returns a proper value. Dynamic Yield enables you to do this with our own version of the q library in the DYO object (DYO.Q).
Notes:
- If native JavaScript promises are supported, DYO.Q uses them and extends their functionality to ensure that the performance matches the native implementation. This means that if you've already implemented DYO.Q, there's no need to change it. However, if you are still making a decision regarding your implementation, we recommend using native JavaScript promises.
- Even if you decide not to use the q library, your code must include a reference to the library for the evaluator to run asynchronously. The reference can be commented out in the code, for example: //DYO.Q
- Do not give different variables similar names, because this can cause interference in the running session.
Evaluator code examples
DYO.Q(DYO.waitForElementAsync("", 1, 10, 100)).then(function(elements) {
return parseInt(elements[0].textContent);
});
DYO.Q(DYO.waitForElementAsync("",1, 10, 100))
.then(function() {
return "True";
}
);
DYO.Q(DYO.waitForElementAsync("",1, 10, 100))
.then(function(elements) {
return parseFloat(elements[0].textContent.replace(/[^0-9\.]+/g,""));
}, function() {
return 0;
});
Return the total cart value as taken from the dataLayer attribute, for sites that are integrated with Google Analytics. This assumes the dataLayer is at position 0. You can also add a loop to discover the position of the dataLayer if the position is not 0.
//max retries & interval duration can be changed, make sure you are accessing the right position in dataLayer - in this example its the first index in the array
var MAX_RETRIES = 5;
var FALLBACK_VALUE = 0;
var INETRVAL_IN_MS = 100;
DYO.Q.Promise(function(resolve) {
var retryCounter = 0;
var interval = setInterval(function() {
if (typeof dataLayer === 'object' && typeof dataLayer[0] === 'object') {
clearInterval(interval);
resolve(parseFloat(dataLayer[0].cartValue) || FALLBACK_VALUE);
} else {
retryCounter++;
}
if (retryCounter > MAX_RETRIES) {
resolve(FALLBACK_VALUE);
clearInterval(interval);
}
}, INETRVAL_IN_MS);
});
try {
(function() {
var STRATEGY_ID_TO_CHECK = ;
var MAX_PRODUCTS_TO_CHECK = ;
if (!DYO.Q || !DYO.recommendationWidgetData) {
return;
}
var deferred = DYO.Q.defer();
DY.API('callback', function() {
DYO.recommendationWidgetData(STRATEGY_ID_TO_CHECK, {maxProducts: MAX_PRODUCTS_TO_CHECK}, function(err, data) {
if (data && data.slots && data.slots.length) {
deferred.resolve(data.slots.length);
} else {
deferred.resolve(-1);
}
});
});
return deferred.promise;
})();
} catch (e) {}
const THRESHOLD = 50; // Cart threshold
const CART_TOTAL_SELECTOR = '.js-cart-totals__total' // Cart selector per site
DYO.waitForElementAsync(CART_TOTAL_SELECTOR).then((elements) => {
const cartValue = parseFloat(elements[0].textContent.replace(/[^\d.-]/g, ''));
return Math.max(THRESHOLD - cartValue, 0);
});
For example, use this evaluator to return the brand of the page.
const DEFAULT_VALUE = '';
const CSS_SELECTOR = '';
DYO.Q(DYO.waitForElementAsync(CSS_SELECTOR, 1, 100, 10))
.then(function(elements) {
var el = elements[0];
return el.textContent;
}, function() {
return DEFAULT_VALUE;
});
var DEFAULT_VALUE = 'Unisex';
var CSS_SELECTOR = '.customer-gender';
DYO.Q(DYO.waitForElementAsync(CSS_SELECTOR, 1, 100, 5))
.then(function(elements) {
var el = elements[0];
return el.textContent;
}, function() {
return DEFAULT_VALUE;
});
Writing evaluators for template variables
To display the evaluator value inside a variation (as opposed to using it for a targeting condition), the evaluator cannot be asynchronous, and using the q library and a promise is not supported. Its value must return immediately upon variation rendering. For example, an evaluator that returns the page language:
try{
(function(){
if (DY.recommendationContext && DY.recommendationContext.lng){
return DY.recommendationContext.lng;
}else{return 'NA';}
})();
} catch(e) {}
Debugging evaluators
Run the following API in the browser's console to check the value that an evaluator returns. Replace "EVALUATOR_ID" with the evaluator's ID you are debugging (go to Assets › Evaluators to see the IDs of all of your evaluators).
DYO.Q(DYO.CoreUtils.safeEval(DYO.oevals[EVALUATOR_ID].code))
.then(function(result) {
console.log("Returned value from evaluator:", result);
});
Targeting based on evaluator values
As soon as an evaluator is created, it appears under the Custom Evaluator condition, under the Where? category. A list of all evaluators is available as part of creating the condition. Depending on the type of value set for the evaluator, you can select the operator and values in the condition. Learn more about targeting conditions.
Rendering the evaluator value in a template
It is sometimes useful to render an evaluator value in a template. For example, if user's first name exists on the page, and you want to show a personal message with the user's first name. You can do this by changing the variable type to Evaluator.
This replaces the variable with the evaluator value. You can also set a fallback text, in case the evaluator doesn't return any data.
Note that for an evaluator value to display inside a template, the evaluator can't run asynchronously. See the code example earlier in this article.
See Creating Templates to learn more about variables and templates.
Filtering recommendations based on evaluator values
You can use evaluators as rule values in strategy custom filters to get recommended products based on dynamic data. For example, you can set an evaluator to request recommended products that match information about a user that is available in the session, such as gender or location.
To use an evaluator, select Use real-time value in the rule settings. All relevant evaluators are displayed in a dropdown menu.
For more information about strategy rules, see Recommendation Custom Filter Rules.
Copying evaluators between sites
You can copy any evaluator to a different site in the same Dynamic Yield account. Hover over the evaluator, click the Copy button, and select the destination.
Viewing experiences affected by each evaluator
In the evaluator list, you can see how many experiences and strategies are using each evaluator as a targeting condition or custom filtering rule in the Used by column. Click the number to drill down and see every experience or strategy that is using the evaluator. This is important to check before editing or deleting an evaluator, to make sure you are aware of how the change will affect your site.