Apply JS
How to use the Apply JS code section of the Template Builder for Optimizely Web Experimentation and Optimizely Personalization
You can use the Apply JS code in Optimizely Web Experimentation and Optimizely Personalization to inject the experience template onto the page. At a minimum, it should take the HTML and insert it at a selector (which can be specified as a field or hard coded). You can use utilities like waitForElement
to control the timing of how your code runs. Some templates can have more complex logic, like calling out to an external service.
The scope of the Apply JS code includes:
extension
– The configuration of the extension, including all fields as properties, likeextension.height
.extension.$html
– The compiled HTML.extension.$render
– A function to compile the HTML template, which is helpful for asynchronous data.extension.$id
– The ID of the extension, liketop_banner
.extension.$instance
– A unique identifier for a specific template instance. If the template is used more than once on a page, each one has its own instance, likeAE8D40E3-785E-4A31-A9DF-4ED6E0681366
.
When all the template data is available immediately, extension.$html
automatically renders the template into final HTML. However, when you want to use a template with asynchronous data, you can use extension.$render
to compile the HTML template with a specific context. The render function takes an object with each value to pass to the template.
var utils = window.optimizely.get('utils');
// Insert at a hard-coded position
$(document).ready(function() {
$('body').prepend(extension.$html);
})
// Let the user choose the selector
utils.waitForElement(extension.selector).then(function() {
$(extension.selector).append(extension.$html)
})
// Render using asynchronous data
recommender.fetchRecommendations(productId).then(function(recos) {
var products = recos.slice(0, extension.max);
var html = extension.$render({
extension: extension,
products: products,
});
$(extension.selector).after(html);
}
Updated 16 days ago