Javascript document.write脚本的计时

Javascript document.write脚本的计时,javascript,asynchronous,google-analytics,timing,Javascript,Asynchronous,Google Analytics,Timing,看起来此代码导致了计时问题。执行此脚本后,ga.js将在什么时候运行?如果以这种方式注入ga.js,我们如何确保它已执行?(另一个组件取决于此) var gaJsHost=((“https:==document.location.protocol)?”https://ssl." : "http://www."); write(unescape(“%3Cscript src=”+gaJsHost+“google analytics.com/ga.js”type='text/javascript'

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


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

我知道这并不能严格回答您关于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的文件。

它应该同步加载和执行,在执行
write
命令后可以直接使用。您有什么时间问题?ReferenceError:\u gat未定义,但仅在某些情况下。通过将脚本块移动到页面顶部而不是底部来缓解。这就是我所想的,
document.write
将同步执行,但是脚本标记的加载在另一个时间段上,因为它正好被注入到所有http请求的中间。除非捕获它的加载事件,否则您不知道。因此GA建议将此脚本放在head标记中。您在哪里使用
\u gat
(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);
  })();