(The below is referring to the Optimizely X snippet JS API.)
For those seeking to interact with the Optimizely snippet's API, there are two phases of execution to keep in mind:
- Pre-initialization: The time before the Optimizely snippet is evaluated by the browser. Most folks have the
<script>
tag in the <head>
of the document, and it is evaluated synchronously. In this case, all the JS code appearing above the script
tag is the code that falls in this phase.
- Post-initialization: The time after the Optimizely snippet is evaluated. For the common case described above, this is everything below the
script
tag. nit: This is actually a simplification; the JS API is actually available slightly earlier, during the initialized lifecycle hook onward.
In some cases, one wants to "pre-push" or enqueue calls to the API, before Optimizely has initialized (i.e., during phase 1 above). At that time, you can write JS that sets window.optimizely
to an array of API calls (each of which is an object).
During initial evaluation, the Optimizely snippet consumes any pre-pushed API calls present in the window.optimizely
array (if it exists), and then assigns to window.optimizely
the object that has the get
function that's documented throughout the docs. As a result, code that's evaluated post-initialization should expect to interact with the initialized API, optimizely.get(...)
.
It's also worth highlighting that the means of making API calls in both phases superficially resemble one another: the pre-init option is an array, so has a push
method; the API object that's available post-init also has a push
method. They both take the same parameter: an object defining an API call.
In the example you gave, an API call to register with the activated
lifecycle hook is pre-pushed to the window.optimizely
array of pre-pushed API calls. When the browser evaluates the snippet, it will execute any such calls.
Please let me know if that makes sense or not!
source: I work at Optimizely on the team that owns the snippet.