Where to put the Google Analytics code

I know this question has been asked before, but since Google contradicts its support, I was confused.

When generating the Google Analytics code, Google Analytics tells me to set the tracking code immediately after the open tag: print screen google analytics

However, I read on the Google support forum that it should be inside the <head> .

https://support.google.com/analytics/answer/1008080?hl=en-GB

Insert your snippet (no change, in full) on each web page that you want to track. Insert it immediately before the closing </head> .

Does anyone know which one is better?

+6
source share
2 answers

As long as it fits correctly between the <script> tags, it should work anyway. The only compromise is that:

  • including it in the <head> section will result in a slower rendering of the page (because it will execute js before parsing the rest of the page)
  • including at the bottom of the page, people who land on your page, stay for 3 seconds and leave may not be considered.

The latter will not happen on small pages, but I have seen it happening in forums and blogs where there is a lot of html rendering, a couple of feet of scrolling below the fold, and the completion of the page takes a few seconds. In these cases, people may leave before performing the GA fragment.

The current analytics code is asynchronous, so even if you put it in the head, it should not affect the rendering time, but within a few milliseconds.

TL / DR is about the same when it comes to regular pages

+7
source

As long as you post the code as it appears on Google, tracking will fire.

The higher you have the code on the page, the better your statistics will be.

For example, if you have a user with a slow Internet connection (I think a smartphone with a bad signal), and your page takes 3 seconds to load. If you have the tracking code above on the page, the code will fire earlier and will begin to track the user's time on the site, including the bulk of the download time.

Say in the above example that the GA code is the latest tag on the site, and after 2 seconds the user sees the link they are looking for, and clicks that link before the page is fully loaded. In this case, the GA code will never work from the bottom of the page, and you missed the analytics on hit / visit / visitor, which really went to your site.

Having a GA code in the header or at the top of your code does NOT need to slow down loading time. You can invoke GA code asynchronously so that it does not slow down the rest of the load (documented here: https://developers.google.com/analytics/devguides/collection/gajs/ ).

+1
source

Source: https://habr.com/ru/post/977764/


All Articles