Why doesn't Google Optimize javascript execute on page refresh?

3.6k Views Asked by At

I'm using Google Optimize to run an A/B experiment on a page, by injecting a line of Javascript:

$(document).ready(function(){console.log(1);});

When I run the experiment and view the targeted page in a new incognito window, "1" is successfully logged to the console.

But if I refresh the page, nothing is logged to the console. I can navigate to and from the page, but nothing is ever logged.

I can only get it to work again if I close my incognito session and start a new one.

It's as if Optimize is only executing the script the first time the variation is seen by a session user?

How can I get the JS to run every time the page is viewed in a session?

Note: I have tried placing the code in the body and the head, both after opening tag and after closing tag.

1

There are 1 best solutions below

0
On

Thanks to some help from a Google Employee here, I managed to work out that JQuery was the hold-up. On first incognito load, Optimize wasn't yet cached and was taking longer to load than JQuery, so by the time it executed my custom JS could run OK.

But on refresh, the cached Optimize was loading before JQuery, meaning that my custom JS was failing.

The solution was to strip out JQuery and do what I needed with plain vanilla Javascript.

For my simple example above, I can simply call console.log(1); without wrapping it.

In my real work, I was trying to set placeholder text in an input field. Doing this in plain Javascript worked fine:

document.getElementById('theElement').placeholder = 'The Text';

Hope this helps someone.