JavaScript execution
This topic describes the timing of when JavaScript code is executed.
Optimizely Web Experimentation lets you build experiences using a visual editor or make more sophisticated changes by writing your own custom code. To give you full control over the execution of that code, the timing of when code is applied has changed, and new utility functions for adjusting that timing have been added.
Timing
Web Experimentation separates visual changes from custom code. When you make a change in the visual editor, the corresponding jQuery does not appear in the code box. Instead, the change is stored in a JSON data structure and applied at runtime when the target selector is ready.
Custom code runs immediately and exactly as written, often before the DOM is ready. For example, the following code has no effect if the Optimizely snippet is in the head tag, because the body element does not exist yet:
$("body").css("background-color", "red");To delay execution until the DOM is ready, use jQuery's document.ready function.
// Change the background when the DOM is ready (may cause flashing)
$(document).ready(function() {
$("body").css("background-color", "red");
});To apply the change as soon as the target element loads and avoid flashing, use the waitForElement utility.
var utils = window.optimizely.get('utils');
utils.waitForElement('body').then(function() {
$("body").css("background-color", "red");
});You can also use the CSS option under Custom Code to make style changes without managing timing. CSS changes are applied by appending a style tag to the head tag:
body {
background-color: red;
}Custom code is applied synchronously in the following order:
- Project JS
- Campaign JS
- Campaign CSS
- Experience or experiment JS
- Experience or experiment CSS
- Visual editor changes
NotePersonalization campaigns and Web Experimentation experiments can execute in parallel. Avoid assuming dependencies between them, or optimizing the same element across multiple campaigns and experiments.
Get function
The get function lets you access several useful properties and utilities after the platform has initialized.
NoteUnlike
push,getis not available before the Optimizely snippet executes or in Project JavaScript. It is available in all other custom code and after the Optimizely snippet has been executed.
Updated 20 days ago
