document.write 注入 javascript 的时间

Timing of document.write injected javascripts

看起来这段代码导致了计时问题。执行此脚本后什么时候会 ga.js 运行?如果以这种方式注入,我们如何确定 ga.js 已经执行? (另一个组件依赖于它)

 <script type="text/javascript">
                var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
                document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
    </script>

我知道这并不能严格回答您关于 document.write 的问题,但它应该可以解决您的问题。

ga.js 被设计为异步使用。你应该能够做这样的事情:

var _gaq = _gaq || [];
_gaq.push(function(){
    // Use _gat here freely
});

加载到 ga.js 后,将处理推入 _gaq 的函数。

另外,您使用的代码似乎是相当旧的版本。较新的版本不使用 document.write。

(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

如果您决定更新分析跟踪代码,我建议您直接跳转到 Universal Analytics,它使用名为 analytics.js 的不同文件。