Behaviour of external scripts along the Optimizely snippet
Hi, I am aware that Optimizely highly recommends to place the snippet on the HEAD tag and modify HTML tags on the body tag in each variation of an experiment, but here is my scenario.
I have a third party script, lets say my_script.js which loads synchronously in the HEAD tag (it has to be there) and, as the Optimizely snippet, changes content of the body as well as the Optimizely script. As this script is loading synchronously, but executing asynchrnously, what type of race condition do I have with the Optimizely snippet? Which executes first if both manipulate DOM elements of the BODY tag? Does the order in the HEAD tag matter? Is there a way to prevent this race condition to happen?
Here are some concerns for implementing Optimizely async. As you're loading it sync and executing it async, the effects might not be too big. I'd suggest you test it out.
If you implement Optimizely async, this means that your page will likely be loaded before Optimizely is loaded every single time. This will cause two issues:
- Flashing of original content before your changes
- Optimizely integrations not working correctly / not being supported when the snippet is implemented async.
Optimizely has no chance to apply any sort of variation change before your page is already displaying. There's is a big chance that your page will display every time before the snippet can execute any code. Flashing issues are almost always resolvable, as long as the Optimizely snippet is implemented in the optimal way on the page: synchronously and at the top of your site's <head> tag.
If Optimizely is loaded/executed async, the calls to other analytics tools might not be done in the correct order. In general for most integrations, this is the order of operations that needs to happen:
- Optimizely loads
- The other analytics tool loads and sets up the tracker
- Optimizely adds information to the tracker
- The other analytics tool sends the information from the tracker to its servers
If you load/execute Optimizely async, this will likely sometimes have an impact on the order in which this happens, and sometimes not, with the risk of making integrations less reliable.
Does that answer your questions?
But how can I ensure that my script.js (which is executed when the DOM is ready) is executed AFTER only and only the Optimizely snippet? Is there an API where I can insert my script being sure Optimizely has executed?
If you're looking to execute your script after Optimizely's, you can simply build the script and append it accordingly. In the following case, your script would fire as you'd expect: