Load Google Analytics from jQuery document ready?

2019-02-17 10:13发布

The problem is that GA sometimes takes a little while to load, and my jQuery ready() functions don't run until it's done. I'd like to move the GA code itself to the end of the ready() function. I'm not looking for extra click tracking integration - I just want my ready() scripts to run first.

My questions are: 1) Will moving the GA code break their stat tracking in any way? And, 2) Do I need to emulate their use of two script tags (one that generates the external script tag, and one that calls the function)? If so, why, and what's the best way to do that in a jQuery function?

To explain #2, here's the GA code that currently goes just before the closing body tag:

<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-8704511-1");
pageTracker._trackPageview();
} catch(err) {}</script>

3条回答
何必那么认真
3楼-- · 2019-02-17 10:48

The reason there are two script blocks is because the script in the first block inserts a reference to the Google Analytics javascript file between the two blocks. If it would all to be in the same block, the tracker would try to be initialized before it had been loaded. So #2 is definately true, you would need to have or emulate two script tags.

查看更多
迷人小祖宗
4楼-- · 2019-02-17 10:53

It looks like Google has tackled this issue as well - see this more recent Stack Overflow question

查看更多
登录 后发表回答