GA Async ‑‑ Why And How Does It Work?
Google Analytics does all sorts of cool things that are completely opaque to non-techies (like me). The “asynchronous ga.js snippet” is a great example of that. I wanted to understand this one in my usual tech-for-non-techies fashion, so here goes:
Before async, GA told us all to put our analytics code at the bottom of the page. There was a good reason for this. Web pages often load from top to bottom, so having the code at the bottom of the page enhances the user experience. This is web-person speak for, “Let’s keep users from twiddling their thumbs while waiting for the GA code to load.” Google Analytics isn’t all that “heavy” to start with, but I remember a day not too long ago when many Google servers went down. Not only couldn’t we read our gmail or our Google Docs, but web pages that had the Google Analytics code near the top of the page wouldn’t load.
The downside of the “bottom of the page” is that users who are in a hurry (and who isn’t?) may navigate away from a page before the code loads. When that happens, we no longer get to see the pageview, correct time on site, etc.
Enter the async code. Although Google Analytics uses the analogy of a separate lane for traffic, it still left me wondering, “now why exactly does this work?”
So here is how:
When the Google Analytics tracking code does its usual thing, it makes a request for ga.js. Then you execute all the tracking functions for your page, whether it’s just tracking the pageview, setting a custom variable, recording an ecommerce transaction, etc. With the old version, all those functions wait for the ga.js script to load. If you’ve put your code at the top of the page, the rest of your page will also be waiting. If you’ve put your code at the bottom, GA will be waiting on the rest of the page.
With the new async code, everything that you want your page to do — set those custom variables, or manage your ecommerce, or what have you — now gets queued up. The page makes the request for ga.js, but nobody waits for it except other GA functions that you have on the page.
When the server responds, all the other GA functions in the queue are then allowed to do their thing. Variables can get set, scripts can run, you name it. This way, you can have the code at the top of the page without holding up the rest of the content. And because it’s at the top, it’s likely to finish before the bottom of the page completes loading, so you’re less likely to lose data to visitors clicking off the page before it’s completely loaded.
You can read more about the asynchronous code at on the Google Analytics code site.