How do I run Javascript on a document that's ready in Google Optimize?

How to run javascript when loading a window or document in Google Optimize campaigns? It looks like it allows me to select DOM elements all the way down to Body, but I need to run js on the finished document.

+3


source to share


1 answer


This is how I talk about it:

  • Change the experiment variant in the editor.
  • Click the Select Items icon (rectangle in the upper left corner)
  • In the Member Selector, enter body

    .
  • Click the Add Change button and select Javascript. This will bring up a dialog that will allow you to enter the JS function that will be called on the body.
  • Paste the code you want to run there and make sure the After closed tag option is selected.

Due to the nature of Google Optimize, I would expect it to not start messing around with DOM elements until they are loaded. And since you select the After closed tag option of the body tag, which should ensure that all elements have been loaded into the DOM.



However, if you want to be 100% sure, you can write a function like this.

function runOnLoad() {
    console.log('this will only run when window is loaded');
}
if(document.readyState === "complete") {
    runOnLoad();
} else {
    window.addEventListener("onload", runOnLoad, false);
}

      

This code snippet was adapted from How to check if a borderless DOM is ready?

+1


source







All Articles