简体   繁体   English

为什么Google Optimize javascript无法在页面刷新时执行?

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

I'm using Google Optimize to run an A/B experiment on a page, by injecting a line of Javascript: 我通过插入一行Javascript,使用Google Optimize在页面上运行A / B实验:

$(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. 当我运行实验并在新的隐身窗口中查看目标页面时,“ 1”已成功登录到控制台。

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? 好像Optimize仅在会话用户第一次看到变体时才执行脚本?

How can I get the JS to run every time the page is viewed in a session? 如何在会话中每次查看页面时使JS运行?

Note: I have tried placing the code in the body and the head, both after opening tag and after closing tag. 注意:在打开标签后和关闭标签后,我都尝试将代码放置在身体和头部中。

Thanks to some help from a Google Employee here , I managed to work out that JQuery was the hold-up. 由于这里的Google员工提供了一些帮助,我设法弄清了JQuery的作用。 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. 首次隐身加载时,Optimize尚未缓存,并且加载时间比JQuery长,因此在执行我的自定义JS时可以运行OK。

But on refresh, the cached Optimize was loading before JQuery, meaning that my custom JS was failing. 但是在刷新时,缓存的Optimize在JQuery之前加载,这意味着我的自定义JS失败了。

The solution was to strip out JQuery and do what I needed with plain vanilla Javascript. 解决方案是剥离JQuery并使用普通的Javascript执行我需要的操作。

For my simple example above, I can simply call console.log(1); 对于上面的简单示例,我可以简单地调用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: 用普通的Javascript可以正常工作:

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

Hope this helps someone. 希望这对某人有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM