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

人走茶凉 提交于 2019-12-04 19:00:37

问题


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.


回答1:


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?




回答2:


if the above code doesn't work.

Try to use:

document.onreadystatechange = function() {
    if(document .readyState === "complete") {
      console.log('this will only run when window is loaded');
    }
}

Ref: https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState



来源:https://stackoverflow.com/questions/43455435/how-do-i-run-javascript-on-document-ready-in-google-optimize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!