Why does Google recommend putting Analytics asynchronous code * after * scripts in <head>?

Why does Google recommend putting js scripts in front of analytic asynchronous tracking code in your html? http://code.google.com/apis/analytics/docs/tracking/asyncMigrationExamples.html

Here is a quote:

"Note. To ensure the most optimized operation of the asynchronous fragment in relation to other scripts, we recommend placing other scripts on your site in one of the following ways: before the tracking code fragment in the section of your HTML"

+8
javascript google-analytics
source share
2 answers

The task of asynchronous analytical analysis is to load a more intensive script that checks the user's browser to get all kinds of information to identify them, so it can report to the analytics server. However, since all analytics data are not critical for the usability of the page, Google wants to launch it with the convenience of a browser.

In theory, they could advise the programmer to add an asynchronous fragment to the bottom of the page as the last element of the body. However, to allow the programmer to capture user interface events for sending to analytics, they want to make the _gaq variable to be used at an early stage. For example, you might have a button: <button onclick="_gaq.push(...)">Track</button> . By making _gaq available at an early stage, a small bit of code in the asynchronous fragment will queue these messages, and the heavier ga.js will send them to the server later.

Now some details: ga.js loaded by adding a new <script> element to the head of the document using the async attribute set. IE and WebKit will asynchronously load <script> tags inserted from scripts. Firefox and Opera will evaluate the async attribute and also load the script asynchronously. In any case, ga.js loads asynchronously, with the convenience of a browser.

Finally, once ga.js is executed without blocking the page display due to asynchronous loading, it can do the hard work of collecting all user data and any messages in the _gaq queue and sending them to the server.

Summary: This approach uses a small built-in script that initializes some key variables, such as _gaq , so that your page can access until the full ga.js script is ready. This small script also dynamically adds the <script src="ga.js"> to the document so that most browsers will load and execute it asynchronously without blocking page rendering or evaluating critical scripts.

+4
source share

When the browser loads the page, it does it from top to bottom. Browsers have a limited number of β€œconnections” that it can use to download documents related to the part. If you place their script above yours, your own scripts may not load until you complete them. Analytical code is not critical to the functionality of the page, so we can save it for the very last.

+2
source share

All Articles