Load Google Analytics from jQuery document ready?

2019-02-17 10:18发布

问题:

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>

回答1:

A similar question here:

  • How to dynamically load Google Analytics (JavaScript)?

And the accepted answer here:

  • Better Google Analytics JavaScript that doesn’t block page downloading


回答2:

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



回答3:

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.