Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run Javascript on Document Ready in Google Optimize?

How do I run javascript on window load or document ready in Google Optimize campaigns? It seems like it allows me to select DOM elements all the way up to Body, but I need to run js on document ready.

like image 440
Stewie Griffin Avatar asked Apr 17 '17 16:04

Stewie Griffin


People also ask

How do I move elements to Google optimize?

You can change this behavior by clicking on the "MOVE SETTINGS" option in the right section of the app bar (at the top of the page). The default setting is "Reorder," but if you change this to "Move anywhere" you'll be able to move an object out of the group.

What is Optimize js?

The Optimize JavaScript API allows you to use your own JavaScript code to make changes to variants using callback functions. You can also choose to combine these code changes with edits made using the Optimize visual editor.

What is a custom JavaScript?

Custom JavaScript targeting allows you to inject JavaScript into a page, then target your experiments based on the value that the JavaScript returns.


1 Answers

This is the way I go about it:

  1. Edit your experiment variant in the Visual Editor.
  2. Click on the Select elements icon (the rectangle in the top left corner)
  3. In the Element Selector field, type in body.
  4. Click the Add change button and select Javascript. This will bring up a dialog that allows you to input a JS function that will be called for the body.
  5. Put in the code you want to run in there and make sure the After closing tag option is selected.

Because of the nature of Google Optimize, I would expect that it wouldn't start messing around with DOM elements until they are loaded. And because you select the After closing tag option on the body tag that should ensure all elements have been loaded in the DOM.

However, if you want to be 100% sure, you could 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);
}

That code snippet was adapted from How to check if DOM is ready without a framework?

like image 122
Maxime Rainville Avatar answered Oct 24 '22 06:10

Maxime Rainville