1 min read

Where to add Google Analytics code?

Where to add Google Analytics code?

If you use Google Analytics, one of the first questions you find yourself asking is “where to add the Google Analytics code?” on your page. The answer to this question was usually right before the closing </body> tag since earlier versions of the analytics code was synchronous. Hence it was best practice to include the code towards the end of your page (at which point most of the page content was already visible on the screen) in order to provide a better end user experience.

With the newer version of the code — which is asynchronous — Google recommends that the tracking code is included right before the closing </head> tag. Since the code runs asynchronously it should no longer impact your page load time as it does not stop page rendering. This also has the added benefit of making sure the visit is tracked even if the user decides to navigate away before the whole page is loaded.

Note that you might not always be able to control this behavior precisely. For example, if you are using WordPress, the theme selected will usually provide a configuration option to add the tracking code. Where your Google Analytics code gets placed will then depend on how the theme author implemented the page setup. Of course you can change the underlying code in the theme to fix this which might create additional headache each time the theme gets updated.