Dev GuideAPI Reference
Dev GuideAPI ReferenceUser GuideProduct feedbackGitHubNuGetDev CommunitySubmit a ticketLog In

Apply JS

This topic describes the Apply JS code section of the Extension Builder.

The Apply JS code is used to inject the extension onto the page. At a minimum, it should take the HTML and insert it at a selector (which can itself be specified as a field or hard coded). You can use utilities like waitForElement to control the timing of how your code runs. Some extensions will also 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, e.g., extension.height
  • extension.$html – The compiled HTML
  • extension.$render – A function to compile the HTML template on the fly, useful when dealing with asynchronous data (see below)
  • extension.$id – The ID of the extension, e.g., top_banner
  • extension.$instance – A unique identifier for a specific instance of the extension. If the extension is used more than once on a page, each one will have its own instance. Example: AE8D40E3-785E-4A31-A9DF-4ED6E0681366

When all the template data is available immediately, extension.$html will automatically render the template into final HTML. However, when you want to use an extension with asynchronous data, e.g., based on an AJAX request, 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 through 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);
}