Disclaimer: This website requires Please enable JavaScript in your browser settings for the best experience.

The availability of features may depend on your plan type. Contact your Customer Success Manager if you have any questions.

Dev GuideAPI Reference
Dev GuideAPI ReferenceUser GuideLegal TermsGitHubDev CommunityOptimizely AcademySubmit a ticketLog In
Dev Guide

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, like extension.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, like top_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, like AE8D40E3-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);
}