Why does google recommend putting js scripts in before the analytics asynchronous tracking code in your html? http://code.google.com/apis/analytics/docs/tracking/asyncMigrationExamples.html
Here's the quote:
"Note: To ensure the most streamlined operation of the asynchronous snippet with respect to开发者_如何学Go other scripts, we recommend you place other scripts in your site in one of these ways: before the tracking code snippet in the section of your HTML"
The asynchronous analytics snippet's job is to load a more intensive script that inspects the user's browser for all sorts of information to identify them, so it can report back to the analytics server. However, since all this analytics data is not crucial to the usability of the page, Google wishes to run it at the browser's convenience.
In theory, they could advise the programmer to add the asynchronous snippet to the very bottom of the page, as the last element of the body. However, in order to allow the programmer to capture UI events to send to analytics, they want to make the the _gaq
variable for use early on. For example, you might have a button: <button onclick="_gaq.push(...)">Track</button>
. By making _gaq
available early on, the small bit of code in the asynchronous snippet will queue up these messages and the heavier ga.js
will send them off to the server later.
Now, some implementation details: ga.js
is loaded by adding a new <script>
element to the document head with the async
attribute set. IE and WebKit will asynchronously load <script>
tags inserted from scripts. Firefox and Opera will honor the async
attribute and also load the script asynchronously. Either way, ga.js
is asynchronously loaded, at the browser's convenience.
Finally, once ga.js
is executed, without blocking the page rendering due to the asynchronous loading, it can do the heavy work of collecting all of the user's data and any messages in the _gaq
queue and send them to the server.
Summary: This approach uses a small inline script that initializes some key variables like _gaq
that your page can access before the full ga.js
script is ready. This small script also dynamically adds a <script src="ga.js">
tag to the document in such a way that most browsers will download and execute it asynchronously, without blocking the rendering of the page or the evaluation of critical scripts.
As the browser loads the page, it does so from top to bottom. Browsers have a limited number of "connections" it can use to load externally linked documents. If you put their script above yours, your own scripts might not be loaded until theirs is complete. The analytic code is not critical to the functionality of the page, so we can save it for the very last.
精彩评论