Google Analytics 的两个单独的脚本标签? [英] Two separate script tags for Google Analytics?
问题描述
有谁知道为什么 Google Analytics 需要两个单独的脚本标签?
Does anyone know why Google Analytics requires two separate script tags?
具体来说,他们的说明建议用户将以下代码段嵌入到网页中以进行跟踪:
Specifically, their instructions advise users to embed the following snippet of code into a web page for tracking purposes:
<!-- Google Analytics -->
<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>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-8720817-1");
pageTracker._trackPageview();
} catch(err) {}</script>
为什么用户不能像这样只使用一个脚本块:
Why couldn't users use only one script block like this:
<!-- Google Analytics -->
<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"));
try {
var pageTracker = _gat._getTracker("UA-8720817-1");
pageTracker._trackPageview();
} catch(err) {}</script>
推荐答案
标签按顺序执行.
<script>
如果前一个块没有执行完,则无法执行.
<script>
tags are executed in sequence. A <script>
block cannot execute if the previous one isn't done executing.
第一个 标签负责创建 Google
标签,它将加载外部 js.第一个
执行完毕后,DOM 如下所示:
The first <script>
tag is in charge of creating the Google <script>
tag which will load the external js. After the first <script>
is finished executing, the DOM looks like the following:
<script></script> <!-- First Script Tag -->
<script></script> <!-- Google Injected Script -->
<script></script> <!-- Second Script Tag -->
这保证了第二个 标签在
.js
加载完成之前不会执行.如果第一个和第二个 将被合并,这将导致
_gat
变量未定义(因为 Google 注入的脚本在第一个脚本之前不会开始加载执行完毕).
This guarantees that the second <script>
tag will not execute until the .js
is done loading. If the first and second <script>
would be combined, this would cause the _gat
variable to be undefined (since the Google injected script will not start loading until the first script is done executing).
这篇关于Google Analytics 的两个单独的脚本标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!