I’ve read in many sources that Google’s recommended way to add GA code (link) can slow down page loading. StackOverflow itself does not place it at the header (as Google recommends) but at the bottom of the page.
So should I go with Google, StackOverflow—or should I use jQuery’s getScript?
Google Analytics recommends placing the asynchronous snippet just before the
</head>tag.In the days before the asynchronous syntax, the recommendation was to put it before the closing
</body>tag, to prevent page load blocking. This is no longer a serious concern.The only things this script will do in a blocking way is it will create a simple JavaScript array, insert some basic values, and then execute an anonymous function. The browser will move on and continue to load, while in the background the browser will request
ga.jsfrom Google servers, and then execute a__utm.gifrequest to Google’s servers with the tracking information.Because this script is inserted in a non-blocking, asynchronous way, it doesn’t prevent your content from loading on time. Placing it this early will allow you to track a larger percentage of people, including those who click away when only part of the body is loaded. Further, it reduces the possibility for error if you have event-driven tracking within your page.
Also, because Google Analytics is nearly always served from one of two URLs (Google’s HTTP and HTTPS versions), the file is likely cached on basically any browser your users have, meaning that the script itself won’t have to be transferred.
Simply put, best results are guaranteed if you put that snippet at the end of your
</head>tag.