Where to put your Google Analytics code

16,848

Solution 1

As long as it's enclosed properly between <script> tags, it should work anyway. The only tradeoff being that:

  • including it in the <head> section would result in a slower page rendering (because it would execute the js before parsing the rest of the page)
  • including it in the bottom of the page might not count people that land in your page, stay for 3 seconds and leave.

The latter won't happen in small pages, but I've seen it happen in forums and blogs where there is a lot of html rendering, a couple of feet of scrolling below the fold and the page completion takes several seconds. In those cases it is possible for people to leave before GA snippet is executed.

Current analytics code is asynchronous so even if you put it in the head it shouldn't affect the rendering time but in a few miliseconds.

TL/DR it's about the same when it comes to normal pages

Solution 2

As long as you place the code as it appears from Google, the tracking will fire.

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

For example, if you have a user with a slow internet connection (think smart phone with poor signal) and your page takes 3 seconds to load. If you have your tracking code higher on the page, the code will fire sooner and start tracking the user's time on site, including the bulk of the load time.

Say in the above example, that the GA code is the very last tag on the site, and after 2 seconds the user sees a link they're looking for, and clicks that link before the page has fully loaded. In this case, the GA code may never fire from the bottom of the page, and you've missed analytics on a hit/visit/visitor that actually went to your site.

Having the GA code in the header or near the top of your code DOES NOT have to slow down the load time. You can call the GA code asynchronously to keep it from slowing down the rest of the load (documented here: https://developers.google.com/analytics/devguides/collection/gajs/).

Share:
16,848
Benidorm
Author by

Benidorm

Front-end developer: Javascript, Greensock, Html5, Css3, Animations

Updated on June 17, 2022

Comments

  • Benidorm
    Benidorm almost 2 years

    I know this question is asked before but because Google is conflicting itself in their support I was confused.

    When generating a Google analytics code, Google Analytics tells me to put my tracking code immediately after the opening body tag: print screen google analytics

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

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

    Paste your snippet (unaltered, in it’s entirety) into every web page that you want to track. Paste it immediately before the closing </head> tag.

    Anyone knows which one is best?