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.
This is the way I go about it:
body
.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?