Where Should The Google Analytics Tracking Code Be Placed?


Before I even start talking about this, let’s go to code.google.com for the official recommendation on where someone should place their Tracking Code on their webpages…

The Analytics snippet is a small piece of JavaScript code that you paste into your pages. It activates Google Analytics tracking by inserting ga.js into the page. To use this on your pages, copy the code snippet below, replacing UA-XXXXX-X with your web property ID. Paste this snippet into your website template page so that it appears before the closing </head> tag.

Google Analytics Asynchronous Tracking Code

The Google Analytics Asynchronous Tracking Code

Ok! Thanks for reading, see you next time!

Just kidding, of course it’s not that simple.

So seriously, where should I put my Google Tracking Code?

We actually get people asking us about this a lot. It’s one of the first items in our audits that we look at. What version of the tracking code are you using, and where is it on the page. There are plenty of variations, but the most common one if it’s not completely up to date, is having non-Asynchronous (or ‘traditional’) tracking code, which is placed at the bottom of the page.  So when the first item in our audit says “We recommend you update to the Asynchronous tracking code, and move it’s placement into the <head> of your document, rather than at the end of the <body>” people get worried.

Is it bad to have the Google Tracking Code at the bottom of the page? I read that you should put it there at the bottom, rather than up in the head because it makes your site faster.

Headless mannequin

Should you place the tracking code in the <body>?

The quick and dirty answer is that yes it’s safe to put the new code really anywhere on the page, and for 99% of users, you’ll want to use the Asynchronous code and put it in the head of your document. There are a few exceptions/alterations which I’ll note in a minute.

The less quick part of that answer is that it WAS bad to put the traditional Google Tracking Code in the head of your webpage in the past, so if you read some book or blog purporting to speed up your website extolling the virtues of putting the Google code at the bottom of the page, then they may have been correct once, but they aren’t anymore. The speed of the internet, and all that jazz.

Google released the Asynchronous Tracking code on December 1st, 2009. Prior to that point all we had was the traditional code, and it worked like most other basic JavaScript code. That is to say that it would go one line at a time. So when your browser loaded up a line of code, it would load that line only, and then wait till that line was fully loaded. Then, and only then, would it move to the next line, and then load that line, etc. Like a single conveyor belt. The problem with that design though, is that if you ran into a snag the entire page would hang. So if the Google Tracking Code back then was placed at the top of your webpage in the head of the document, then the speed your site loaded was partly determined by how quickly Google sent you that code. If it took Google 10 seconds to send you that code, that was 10 more seconds your visitor had to wait to view the page. That’s why it was recommended to put that code at the very bottom of the page. That way if it stalled in loading the files from Google, at least your page was loaded first.

The Asynchronous code though works differently. Rather than say a SINGLE conveyor belt, now there are multiple ones, and the rest of your page can load up regardless of how long it takes to retrieve data from Google. The tracking code loads up on its own conveyor, while the rest of your site loads on another.

And on top of that the Asynchronous code is designed to be downloaded only once from Google, and then it’s served from your cache (i.e. it’s saved on your computer and you won’t have to download it again), which makes it that much faster.

You lost me poindexter, what does that mean for me?

It means the asynchronous tracking code averages a 5% improvement in tracking data, with some sites showing 10 and even 20% improvement in their data. If you use Adwords, it closes in on 100% accuracy with the asynchronous code.

The asynchronous code is faster, and therefore you get better more accurate numbers as to how many people are actually visiting your site.

What if I have events or things happening on the page, where I need to record user actions, and the tracking code hasn’t loaded yet?

Well, that problem would also happen if you had the non-async code firing at the bottom of the page, but with async it’s much better. Even if it takes time to load the ga.js file from Google, it’s already set up the tracking variables on the page, and will store the events you perform before the actual file is loaded. Once the file loads, then all the events backlogged will be sent to Google. It’s not PERFECT, but for the most part it will capture events that happen prior to the Google tracking code has even finished loading, and send them after the code has been loaded.

So do I need to move it to the head of all my pages? I have a lot of pages, and that’ll take a lot of time.

Mannequin heads

You can put your tracking code anywhere, but it's better in the <head>

Nope. You can put it anywhere you want really, and It’ll run anywhere on the page whether it’s in the head or the body.  It’s recommended you put it in the head though, so it can be as accurate as possible.

You see, the Pageview is recorded only after that code is loaded up. So the sooner you load the code, the sooner that Pageview is recorded. Let’s say you have a big blog page, and it’s a slow loading one, taking even 10 to 20 seconds to load everything up. If your Google Code doesn’t start until the end of the page, it can get held up, just like the old non-asynchronous code used to hold up OTHER lines of code. Except now it’s holding up the tracking code. If a visitor to your site hits the page, and then leaves it before the tracking code fires the Pageview, then you lose that visitor. They now become a new direct visit to whatever page of the site they landed on. This can make all sorts of data on your site incorrect.

So it’s best practices to use the Asynchronous code in the head of your page, it won’t slow down the rest of your page from loading, and by having it there it won’t GET slowed down by the rest of the webpage either, so it’ll fire sooner, and you’ll get a more accurate count of what pages your visitors visit.

So what are the exceptions? When is it BAD to run the tracking code up in the head?

I mentioned before that there ARE a few exceptions. One is if you’re setting custom variables on the page.

If you set a Custom Variable on your webpage then it will essentially sit on your page, waiting for either a pageview to be tracked, or an event to be called. If you set a custom variable on a page and don’t track a page or an event after it, that custom variable will NOT get passed to Google. Sometimes you might not be tracking any events on a page, but you’ll want to set a custom variable. Because of how code is delivered, it’s possible that custom variable might only get generated AFTER the head document.  Usually a page can be coded so that these variables can be determined before the HTML is delivered and then you can have the custom variables created in the head of the document as well. Maybe it could theoretically be put in the head, but the developers didn’t build the page that way, and you’re not willing or able to have them redo everything. In those cases you can set a Custom Variable anywhere on the page, and then rather than tracking the pageview in the head of the document, you remove this line:

from the Asynchronous code, and then insert it later in the page wherever you like, after the custom variables are set. That way the code loads up, it doesn’t interrupt the page load, and you can then track custom variables on the page itself anywhere they appear, as well as retaining the benefit of loading the tracking code early.

HOWEVER, this can also reduce accuracy, because if a user navigates away before that trackPageview is called, then you’re facing the same problems that the traditional code presented in the first place. Another option would be to use Event Tracking. An event being fired will also submit that queued custom variable, so you could fire an event tied to that custom variable. Essentially a throwaway event.

A couple notes on this:

First we’re setting the Custom Variable, we’re assigning it to key space 1 (of 5), and we’re calling it Status, and setting the value to Logged In. That’ll sit there until an Event or Pageview is tracked.

So we do the event. We set it to a Custom category group, we define the action as PageLoad because a user isn’t specifically interacting with this event. Then we set the Label as to what the event is doing. We add a 0 to the value (you don’t have to add an actual value there if we’re not using it, but I’m personally uncomfortable passing nothing). We also then set the non-interaction value to true. This is also key if you use an event here. If you don’t set it as true, then the event is considered a page interaction, and it will affect your bounce rate from the landing page. Essentially rather than someone coming to your page looking at it and hitting the back button being considered a ‘bounce’ it would not be considered one because the user ‘interacted’ with the site. So we set this to true, so that isn’t considered in that respect.

But wait, I read something on Google’s own support pages that said I shouldn’t do this?

You mean this page?

Yeah, you don’t believe everything you read, do you? That’s old outdated support information.

So if we update is it going to change my data? Like am I all of a sudden going to see more pageviews or something?

It’s possible. It depends on your site, where the code was, what sort of speed and pageload times you have. By updating you should see the data you’re getting change, maybe a little, maybe a lot. But it’ll be MORE ACCURATE data. Here we tend to side with getting the data to be as accurate as possible, even if there is a bit of a break in the levels of reporting.

If I don’t update, will my site continue to track data?

Sure. It probably won’t be as accurate, but depending on your site it’s conceivable it’s not a huge data difference. The main functions are all loaded from the same place, the ga.js file. The main difference is how it loads, how fast it loads or is even cached in your browser, and therefore the accuracy of your data.

So what should I do?

If you’re NOT using the up to date Async code you should update to using that. You’ve really got to have some serious things going on to NOT update. Does it need to be in the head of the document? No, it won’t kill you to have it at the bottom of the page, but if you CAN move it to the top, then you should because it’ll be faster and more accurate. If you don’t know of a reason to keep using the non-async code at the bottom of the page, and you’re not using custom variables… Then really there is no reason to NOT update it and move it to the top of the page. You’ll have more accurate data, you’ll get newer and better tracking features, and more. Come on. Everyone’s doing it.

Sayf is a former LunaMetrician and contributor to our blog.

  • gerry

    Can I have the tracking code in a .js file on my site that I load in the head section or does the code have to be coded directly in the head section?

  • dean

    Can I place a tracking code on a website which I post to? say for example a website that I am listing something for sale (not ebay). If the form to submit a listing on a website allows me to place text on a page and upload images through a form. Can any of these be used to insert a google tracking code so that I can see how many visits I get to my listing on the website?

  • What should a Google sites´ user do to such code? Can not find in Google´s editor.

  • Sayf Sharif

    Google actually wrote a support piece about linking Google Sites with Analytics.


    That should help you out.

  • Sayf Sharif

    Dean, it depends on the site. If you’re not fully controlling the site and don’t own it, it’s most likely against the Terms of Service to insert tracking code there. Also the way it lets you place text might not accept you inserting javascript into their page, as it’s a security risk for them as well.

  • Sayf Sharif

    Gerry, Yes you can place the GA code inside a javascript include that you include in the head of your document.

  • I have inherited a site that uses non-async tracking. The site is .php and is built using . Particularly the header and footer are added this way within the section. Inside the ‘footer’ is where the Google tracking code is located. This has obvious advantages in that from a single location the code appears on every page giving an incredible time savings in not having to insert it on each page individually. OK, my question, can I insert the new Async code the same way? Anything special needed to do this?

  • before this i was using plugin for analytics.. which is also increasing my website load speed.. thanks

  • Charlie

    I would like to update my GA code and use the Asynchronous code before the . But I’m also trying to get my AdSense revenue as accurate as possible within Analytics.

    My AdSense and Analytics accounts are connected. And I’ve set the primary profile in Analytics.

    Does it matter that the Asynchronous Analytics code is in the and the AdSense ad codes are in the ? Would my AdSense data be more accurate in Analytics if I had the GA code at the bottom of the page?

    Wouldn’t it be nice if Google put time stamps on their help articles? 🙂

    Thanks for any insights…

  • Charlie

    Sorry, I’m re-posting this since the form stripped the special characters which renders my previous comment sort of confusing…

    I would like to update my GA code and use the Asynchronous code in the HEAD tag. But I’m also trying to get my AdSense revenue as accurate as possible within Analytics.

    My AdSense and Analytics accounts are connected. And I’ve set the primary profile in Analytics.

    Does it matter that the Asynchronous Analytics code is in the HEAD and the AdSense ad codes are in the BODY? Would my AdSense data be more accurate in Analytics if I had the GA code at the bottom of the page?

  • Sayf Sharif

    Charlie, everything will be more accurate if you load the async code in the head of the page. It’s more likely to actually be worse if it’s at the bottom of the page.

  • I am getting ready to copy & paste Google Analytic’s tracking code (for a single domain) so that my website can be tracked by Google Analytics. However, on one of the instruction pages the following is stated: “Be sure to copy the snippet and paste it directly onto your website using either a text editor or an editor that preserves code formatting. We recommend that you do not use a word processor to copy the snippet from your account. Doing so can add an extra space or change the quotation marks in the tracking snippet, which requires precise formatting in order to work.”
    Well, I’m pretty ignorant about computers. Is the previous statement saying that it is not advisable to use your comuter’s mouse to copy the code and then directly paste it onto each page of my website?
    Also, on most or all of my website’s pages, the closing tag is immediately preceeded by > So I guess I paste the code between the >< ?

  • Sayf Sharif

    Mike, that’s actually a good question.


    There are actually different kinds of quotes. Curly quotes that look like 6’s and 9’s. There are slashy typewriter quotes. And then there are the straight up and down ‘ type quotes and ” type quotes.

    That’s the key part of the copy and paste with a text editor… Because word processors ala Microsoft Word, like to change those plain jane ascii straight up and down quotes with curly quotes or typewriter quotes… And those actually will break javascript code. You NEED the plain quotes for the code to work.

    What I recommend doing if people aren’t sure, is to copy (it’s fine to select with your mouse and choose copy), but then paste it into a text editor, and be sure it’s a text editor. Something like TextWrangler on the Mac, or Notepad++ on the PC. You can use the regular TextPad/Notepad type applications but they often default to not actually being plain text. However if you copy into one of those, you can then select the document to be in plain text usually in the edit or preferences menu for “Make Plain Text”.

    Anything other than plain text and the code will error and not work at all because the quotes will be not quotes according to the browser javascript engine, and poof. No data.

    As far as the placement I’m not sure precisely what you’re saying but if you have another tag that ends with a > before your head tag then yes…

    So if you had say..

    Then you’d put it in between those >< characters right before the


    Hope that helps!

  • I am a new blogger. I follow what you have said, for almost an hour I put an end to my problem. It said there that I have to put it on , it doesn’t work. Now I put it before my Google Analytic Account is now receiving data. My website had a frame it doesn’t work if I post it before the . And as I read your blog, regardless whether I put it before or it still would work depending on my website. Thanks for this.

  • Sayf Sharif

    Pal, I’m having a hard time understanding what your problem is based on what you’ve said. However the word “frame” is a red flag. Frames can play hell with GA code depending on how many you’re using.

    Here’s the GA support page on using Google Analytics with frames.


    It recommends putting the tracking code both in the head of the frameset, as well as before the /body of each page that appears within the frames.

    If you just place the code in the frameset you won’t track any interior pages. Every visit will be just a 1 page bounce visit onto your home page. Having the code within each page that appears in the frames will inflate your pageviews on the site, but you’ll at least pass the correct referral information, etc.

    My only question about that support link is the placing of the code before the close body tag. That might also belong in the head, as that sounds like maybe it’s a slightly older support document from before the async code came out. But it should still work if you put it before the /body tag.

    Hope that helps.

  • Dave

    I am using a host that inserts code just before my closing head tag (a facebook app meta tag: <meta property="fb:app_id"…) which makes it impossible for me to place the analytics immediately before the closing head tag as google suggests. Does it matter if the analytics code is placed in the head, but not right before the closing tag? Thanks.

  • Its a New updated code of google analytics which can post anywhere in the website . but in Head Section itll more safe and active

  • Sayf Sharif

    Dave, as long as it’s in the head you’re fine. Honestly it’ll even work if it’s in the body, but the optimal placement is in the bottom of the head section of the HTML. if your CMS or host inserts code between the tracking code and the /head tag, that’s fine, it won’t affect it. it doesn’t have to be literally right before the head. That’s just optimal placement.

  • Dave

    Thanks Sayf. I’m glad I found your website. It has provided me with a lot of information I can’t find anywhere else.

  • Garrett

    For an eCommerce site is it ok to have the addItem, addTrans and trackTrans after the pageView in the page?

  • Sayf Sharif


    Garrett, in fact you WANT to put the transaction after the trackPageview.

    Here is the example code that Google provides.

    _gaq.push([‘_setAccount’, ‘UA-XXXXX-X’]);
    ‘1234’, // order ID – required
    ‘Womens Apparel’, // affiliation or store name
    ‘28.28’, // total – required
    ‘1.29’, // tax
    ‘15.00’, // shipping
    ‘San Jose’, // city
    ‘California’, // state or province
    ‘USA’ // country
    ‘1234’, // order ID – necessary to associate item with transaction
    ‘DD44’, // SKU/code – required
    ‘T-Shirt’, // product name
    ‘Olive Medium’, // category or variation
    ‘11.99’, // unit price – required
    ‘1’ // quantity – required

    We have tested it in the past and have shown that you can theoretically track a transaction WITHOUT a trackPageview or trackEvent on a page at all, however that is HIGHLY unrecommended and unsupported, and may not always work. Best to put the trackTrans AFTER the trackPageview on the page as directed by Google.

  • katrina

    Hey – thanks for this great article.

    I’m having problems though finding the tracking code from within my Google analytics accounts. Obviously i had them at one point, but i want to update them and make sure they are correct. I can’t for the life of me find where they are and it’s driving me crazy. Searching (and gulp.. posting) on Google help forums, or relying on search results there would drive me absolutley insane beyond redemption. I wonder if you can help me find it??/
    thanks in advance…

  • Sayf Sharif

    Do you mean the tracking code inside Google Analytics itself? The tracking code there which you can use is located within the admin section.

    If you click on the Admin button in the orange top navigational bar within Google Analytics it will probably take you to a profile page. From there you should see on that page a Property ID: UA-123456-1 type number that is underlined as a link. Click that.

    That should take you to the Property Page where you will see the name of the site, and a set of tabs underneath it, the second of which is “Tracking Code”. Click on that. On the next page scroll down to find your code.

  • Monique

    Hi there, interesting article. I run a site using a thesis blog template. The site has different categories – would you advise placing google tracking code for analytics on every category page? Thank you!

  • Sayf Sharif

    You should place the tracking code on every single page of your website, you don’t want it missing from any of them. If your’e using the Thesis template for WordPress I recommend you also install a Google Analytics plugin such as the one by Joost de Valk:


    It’s also available within your website by going to plugins, choosing add new and searching for Google Analytics Yoost. It should be the first one that comes up in the search results within your admin section, and you can install it, and then set it up with your Google Analytics ID and it will place the code on every page of your site.

  • Hi Sayf:
    A client has async code in the header of every page which works fine. And he also has the track trans script just before the tag. Everything is tracking perfectly in Anaytics and we’re getting all the transactional detail in the Ecommerce reports.

    The problem is that all transactions are being attributed the source medium of “direct / none”. I have a goal set for the shopping cart confirmation page, so we know that our Adwords campaigns are converting, but it’s frustrating not to be able to tie them to specific transactions.

    Any suggestions you have would be greatly appreciated.


  • Sayf Sharif

    Barb, if you’re talking about the link in your comment, then I can tell you right away that there is some double tracking going on on the page, with async code in the header, and traditional code at the bottom of the document. The async code seems to have the right referral information, while the traditional has direct/none. I don’t immediately see why this is occuring, but I’d recommend removing that double tracking, as not only are the numbers of visitors doubled, but having both async and traditional code on a page is not recommended by google who say weird things can happen. That alone might solve your problem.

    If that’s not your site, it could literally be a million things from redirects to javascript and document objects on the page doing content changes that could screw things up, and it would really only be answerable by doing some actual work on the site (ie you’d have to pay us to look into it).

    But if it’s that website you linked, then my 5 minute “Doctor it hurts when I do this!” advice is to eliminate the traditional tracker at the bottom of the page and only have the async tracker in the head of the document, and see what happens.

  • Hello,

    I need help regarding the placement of google analytics code. The developers have done split on google analytics visitor code. Code prior to the function called placed in the header tag and function part in the body tag. Their concern was site speed. But I am likely facing the problem in tracking through google analytics. I am not able to track properly any utm_ tag urls. So my question is this might the reason for this.

    Please do help me out.



  • Very useful info, I feel applying analytics code to self hosted wordpress sites is a little difficult. I have written an article on blog as ‘5 reasons to use Google Analytics’ http://bit.ly/Ozp2Ct

  • Sayf Sharif


    Without seeing the actual code I’d have to say… Maybe? It’s generally not a good idea to split the basic code and function between the body and the head of a document. All the basic GA code really should be placed in the head together, it’s a minimal site speed increase as it simply calls the ga code, but does it asynchronously so will not hold up the rest of your page page. if they are more worried about holding up the page, as opposed to reducing your data integrity, and refuse to put all the code together in the head of the document, you might be better off having it put at the end of the page as long as it’s all together.

    At the same time, I would be surprised if doing what your’e describing would be the cause of not tracking campaign tags, particularly if the rest of your code is tracking. Does the page remove the campaign tags at the server level and redirect or anything? If the campaign tags are visible in your location/url bar on your browser, then your GATC should theoretically grab them as long as they are named correctly.

  • Raju

    I want to use Google Analytics on a website developed in PHP. I tried the steps given in Google Analytics Help and copied the analytics code into the overall_header.html file (before the .However, it still doesnt wotk.

    If it helps, the website Im trying to use analytics is a forum powered by phpBB.

    Thanks in advance for the advise.

  • Sayf Sharif

    It’s hard to say specifically Raju. I’ve read that phpBB can cache the header and footer files and it could take a bit for the GA code to become visible. Make sure that you can see the tracking code in the source of the page when you’re on the forum itself. Maybe you put the code in the wrong spot.

    If it’s not there, make sure that your changes to the file are actually showing up in the forum source code as well.

    If the code is in the source, and it’s not tracking that’s a different issue, and one that unfortunately I don’t think I’d be able to support through blog comments.

  • I was connecting all my non-primary AdSense accounts to my Analytics account and adding a few profiles and came across what I guess is the new asynchrynous code. I’ll be updating but wanted to share what others may find helpful as well.

    Directly from Google help in Anaylitics, I found the following guidance and need to know if the order no longers applies because of the new code.

    “The AdSense Analytics Code (ASAC) is the additional snippet of code you must place in your webpage’s HTML if you want to link your AdSense account to multiple domains within your Google Analytics profiles.

    window.google_analytics_uacct = “UA-accountnumber-propertyindex”;

    Note that you must place the ASAC above the AdSense and Google Analytics Tracking code to properly apply your AdSense account to multiple domains.

    Please note that the order of the code snippets is very important. The snippets must be placed in your webpage’s HTML in the following order:
    1. The AdSense-Analytics code snippet at the beginning of the page, just after (only for non-primary domains)
    2. The AdSense ad code
    3. The Analytics tracking code, placed just before the closing tag.”

    The above guidance is directly contrary to what the actual analytics tracking code instructions say about placing it just before the tag. I suspect the other may be outdated, but it is still listed in Analytics help and if the new code has been around since 2009, that should definitely be updated…Thanks

  • Just as a clarification since it stripped the tag references, the order Google says the code must be in is:
    1. The AdSense-Analytics code snippet at the beginning of the page, just after the BODY tag (only for non-primary domains)
    2. The AdSense ad code
    3. The Analytics tracking code, placed just before the closing BODY tag.”

  • Jonathan

    Hi Sayf,

    So happy to see that you’re still responding to comments on this article. It had a lot of great information. I do not have access to the placement of the GA code on the website I work on, and to get it changed would be a long, slow process. I’m trying to incorporate virtual pageviews, nothing too seriously technical, but I’m not getting any results from the tests that I’ve put up. Does having the GA snippet at the end of the page rather than the head, and therefore, after the virtual pageview code keep the virtual pageviews from working, or does it just skew the accuracy. It may be that in the tests that I’m running I’m just not giving the GA code at the bottom of the page time to load.

    Hope that made sense. Thanks!

  • Sayf Sharif


    I understand the frustration from out of data support articles on Google.


    However that support article clearly states that you can put your analytics tracking code in the head of your document, and then the adsense analytics code below it. You will be fine doing so, and you will have greater accuracy in your GA data.

  • Sayf Sharif

    Jonathan, I don’t think I have enough information to really discern the issue. In general though if you had your tracking code at the bottom of the page, and then called a virtual pageview, or tracked an event, from within the page, it should fire. if you have the GATC at the bottom of the page, and you are correctly firing the virtual pageview, then it should get sent to Google. It’s fairly common to see that sort of set up with slightly older sites even running the traditional code, but who use Ajax or some form of dynamic page changing to fire a virtual pageview.

    If it tries to fire inline automatically before the page fully loads however, it won’t fire. Only if it happens as a result of something else. So if you’re for instance using a virtual pageview to show a slider in action on the page, and it loads that slider and fires the pageview, if the page hasn’t loaded fully yet, and the code is at the bottom of the page, it won’t fire.

  • I thought I had analytics because I go to my blogger dashboard and see how many visits I have each day and what pages they viewed.

    But then I used mysitegrader and hubspot and they detected no analytics.

    I’ve followed everything you said – but my problem is simple. I go to template and edit HTML code. I’ve put in the code several places – no luck.

    I don’t know what the “head” section is. I’ve looked for that in the code stream and can’t find what the help section of google analytics says I’ll find.

    I’ll note that I own my website name – so there is a redirect involved. But I use a simple template on Blogger and it seems this should be much easier. LOL

  • Sayf Sharif


    if your site is the one you linked on your post there, then I see your problem. You copied the tracking code correctly, but you pasted it right into the middle of a style sheet, which will cause problems.

    So remove it from there, just copy it and delete it from where you put it, and then scroll down in the code until you see < / head > and paste your tracking code immediately before that.

  • No luck so far. Read the trouble shooting section and removed the gaq pageview code as well. But sill showing not installed. I placed cursor right before and the html code accepted it. have the upright quote marks etc. not sure what’s next.

  • also – if I get this figured out – should I turn on the subdomains tracker – the www. etc.?

  • If the ga code was installed years ago (don’t know when or by who), should we just move it from the body into the head now or should we generate a new code and start over?

  • Sayf Sharif


    It looks like you didn’t remove the original code from the page, so now you have two on your page and it might be erroring out. The second newer one you put in looks like it’s in the correct spot.

    As far as subdomains, are you using any? If you just have that site, then you’re ok with the base GA code.

  • Sayf Sharif

    Moving the code to the head will increase accuracy, so if you can change it to the newer code and move it to the < head > section rather than the bottom of the page, you should get more accurate data. Plus with the upcoming changes to Google Analytics with Universal Analytics, you’re going to want to upgrade your code probably in the next 6 months or so to take advantage of it.


    Just be careful that you don’t have anything special going on, and if you do, be sure to account for it, and then watch your data after the move for things like Self Referrals so you’re sure you retagged every page correctly.

  • Lauren

    Is it safe to place the Google Analytics code in a javascript include file? Also, as of May 24, 2012 our hit counts dropped in half. Any thoughts?

  • Weebly tells me to open up the advanced page settings and just place it there, either in the footer box or the header box. So I did and it seemed al simple until everyone started going on about how I put it in the wrong place and about the except I don’t know what any scripts mean. I just wanted to sort it out. Is is ok or will I need to do something?

  • By the way, I’m not sure whether this should be the right sort of Tracking Code so I’m putting it below

    var _gaq = _gaq || [];
    _gaq.push([‘_setAccount’, ‘UA-37059784-1’]);
    _gaq.push([‘_setDomainName’, ‘weebly.com’]);
    _gaq.push([‘_setAllowLinker’, true]);

    (function() {
    var ga = document.createElement(‘script’); ga.type = ‘text/javascript’; ga.async = true;
    ga.src = (‘https:’ == document.location.protocol ? ‘https://ssl’ : ‘http://www’) + ‘.google-analytics.com/ga.js’;
    var s = document.getElementsByTagName(‘script’)[0]; s.parentNode.insertBefore(ga, s);

  • To be honest, I don’t have a clue how to do this, so can you be VERY simple… 🙁

  • Sayf Sharif


    It’s generally safe to put it in a javascript include file. Hard to say what would account for dropping half your traffic, could be a wide variety of things.

  • Sayf Sharif


    I’m not completely familiar with Weebly but from what I’ve seen you can put it in either the header or footer box in the advanced settings area and the code you have there should work. If it does not work as you copied it above it may need to be contained with

  • krish

    Hi Sayf,
    The google analytic will track the website information for which they have predefined interface i.e. dashboard, reports tools etc by adding the tracker code in header or individual page. But my Question is can I customize those as per requirement such as If I want to track the form data including fields, buttons,social links etc. how many time they accessed and the reports on that.
    If yes then how those data will map to google analytic server.

  • Sayf Sharif


    There are many ways you can customize your tracking past the basic tracking code. For instance you can track something like form abandonment using events.


    I suggest checking out the event tracking guide on Google Analytics website:


    That would be a good place to get started tracking things on your page, other than basic pageviews.

  • Thanks, I think it works now!

  • Thank you for this information. I always add Google tracking code before tag.

  • krish

    Hi Sayf,

    Wish u happy new year.

    I have a query regarding below

    can u please guide me, Tracking of web click data across surveys and ratings within website?


    how to Track web click data across social media within website?

  • krish

    Hi Sayf,

    I founded solution about social media interaction,can u please where I can find tracking code for Skype social media
    and also need help on tracking web click across surveys and rating within website

  • I am using weebly and have tried several times to cut/paste the google analytics into the header as recommended, into the footer as recommended, and in both locations without any success in getting GA detect the tracking code. I’m really green with site publishing and have no clue how to fix this, please help.

  • I meant to say GA tracking code has been cut/pasted into settings without success.

  • Sayf Sharif


    I’d check out the event tracking documentation and experiment with that, it’s probably what your’e looking for. As far as Skype social media I’m not sure what you mean.

  • Sayf Sharif


    I wish i could more directly support you but that goes beyond the scope of these blog comments. I recommend you contact the people at Weebly.

  • Thanks, I have sent an email to weebly and no reply as of yet….they are very slow to respond…

  • Sham Marol

    First of all, very informative article. Now I can find answers to my queries.

    1. Under Admin section, should I create individual profile for each page?

    2. I can see that the tracking code/ID is associated with the property. My question is should I copy and paste the same tracking code on all my web pages. (lets say UA-34898237-2)?

    3. I can see the analytical info for some of the extra pages in GA. Even though the pages are from my website only, I have not included any tracking code for those pages. How can I delete/filter those unwanted pages?

  • Sayf Sharif

    You really don’t want to create a different profile for every page. you should create 2-3 profiles. One that you create and call “unfiltered” and then never touch ever again, and a second that you call something like “base” or “main” and that’s where you would add filters, exclude query parameters, etc. Any changes you make to that profile you should make first in a third “test” profile to make sure you’re not destroying your data before you apply that to your main profile.

    yes that tracking code needs to be the same on all pages on the website.

    If you haven’t included tracking code on those pages they shouldn’t show up in GA, but if they ARE in GA you can use filters to remove them from your profile. Just don’t remove them from your main profile. Do them first ina test profile, and then apply those filters to your main one… While not touching your unfiltered profile.

  • Jan

    Lost. Reading Google instructions multiple times. Reading your instructions. WHERE do I put the code? Do I open up FTP, place in “header.php”? Or in “page.php” or “blog-page.php” (neither of which have a tag (instructions were to place it before the closing tag. Or do I use the site’s editor and put it into one of the templates? When instructions say “Copy and paste it into the code of every page that you want to track,” WHERE do you do that?

  • Sayf Sharif


    Based on the names of your files there, my guess is you’re in a WordPress site. If so I recommend the superb WordPress plugin by Joost de Valk.


    You can also search for it within WordPress by going to Plugins and clicking on the add new button and searching for it. Once activated, you only need to add your UA-XXX-X tracking number and it will take care of the basic setup for you, but let you muck around with advanced settings if you like.

    If you are NOT on wordpress, or if you are, but can’t add a plugin, then you most likely need to open up that header.php file, and do a search for . Where you see that code, right before it, copy in the tracking code that you have gotten from Google Analytics.

    If the site is dynamic, and that header.php file loads on every page, you should be good to go. If there are multiple header files you’ll need to add it to multiple pages.

    Hopefully you ARE actually on WordPress, in which case you would best be served by using that above plugin.

  • Fantastic tips as usual and you were right– I haven’t seen a lot of these before anywhere else! Thanks so much!

  • Tiffany

    I have a public sector website where we are using Google Analytics to track different kinds of data. We recently added a new page to the website and Analytics is providing data EXCEPT page load time data. Any idea why that would be?

  • Sayf Sharif


    1% of your pages by default will get sampled, up to 10k visits. If you have a low traffic site, it’s possible that just none of the 1% of sampled visitors have hit that page yet.

    If you have a smaller level of traffic you can adjust your site sample rate higher, and it’ll be more likely to catch the new page.

  • I have the domain name x.org.uk which points to a web page in y.org.uk/x/page.htm. This is masked so that a user typing x.org.uk will be directed to y.org.uk/x/page.htm but will think he is on x.org.uk

    I just can’t get analytics to work in this configuration? Can you help? I can see the analytics code before tag in view source. All I want to track is events on this page and I have the code in place for that. I don’t get page visits or events on my analytics.

  • Sayf Sharif

    Dabir, it could be alot of things. Are you using setDomainName and is it matching the domain that the code is being served from? If you have it set to _gaq.push([‘_setDomainName’, ‘x.org.uk’]); but it’s actually coming from _gaq.push([‘_setDomainName’, ‘y.org.uk’]); then the tracking code wouldn’t fire. If it’s not that it sounds like something else is incorrect in your tracking code that is preventing it from firing at all, if you’re not even getting pageviews or visits.

    In configurations like what you’re talking about you have to be careful with the setDomainName as well as watching out for Cross Domain tracking and your redirects so that you’re making sure you’re not losing your referral information.

  • Thanks for the info. I have not used _seDomainName, but I will put it in my tracking code to eforce it just in case. I have inserted setDomainName after setAccount see below – I hope that is right:-

    var _gaq = _gaq || [];
    var this_page = “http://y.org.uk/newWebPage”;
    _gaq.push([‘_setAccount’, ‘UA-35721135-1’]);
    _gaq.push([‘_trackPageview’, this_page]);
    (function() {
    var ga = document.createElement(‘script’);
    ga.type = ‘text/javascript’;
    ga.async = true;
    ga.src = (‘https:’ == document.location.protocol ? ‘https://ssl’ :
    ‘http://www’) + ‘.google-analytics.com/ga.js’;
    var s = document.getElementsByTagName(‘script’)[0];
    s.parentNode.insertBefore(ga, s);

  • Sayf Sharif

    setDomainName should only have the domain name in it, and not a subfolder.

    Why are you using _setLocalRemoteServerMode? That line doesn’t seem necessary for your code.

  • At last i reached to the verdict. Believe me, after going through lots of forums, threads, articles, i change the place of code dozen times in my site. Stupid i am.
    Because no one describe the actual reasoning. I was about to sleep i came across your article. Now i know what is this all about and finally, i am pasting code under tag. No more change now. Thanks buddy

  • Oh sorry. the missed mention word “head*” tag. I will putting code in head tag now.

  • This is what I got after I copied my code from Google Analytics and pasted into notebook: I have no idea what i am doing wrong. Will the script be hidden when others view my website???
    s = document.getElementsByTagName(‘script’)[0]; s.parentNode.insertBefore(ga, s);

  • Sayf Sharif

    either that code you pasted is incomplete, or the html in it got wiped out by the comment field. Be careful where you paste code because certain word processing editors will actually change that code and when you finally put it into the HTML page it’ll have errors in it. If your’e copying into a notepad/textpad/text editor make sure it’s in plain text, use the code directly from google, and put it on your website page, and then modify the account number. Go as simple as possible before you add things in to make sure it’s working first.

  • I pasted the code on my website and at the very top there is a white background strip with my GA code in it. Not sure what I have done wrong, but hoping you can help.


  • Sayf Sharif

    your page finally loaded for me. you have the initial script tag duplicated twice in a row. Remove one of those.

    Secondly right before the head tag you just randomly have the UA account number there outside of any other code. Delete that as well.

  • Anna

    Hi Sayf,

    Thanks so much for this article. Our tracking code is placed within the head title, and it is the latest version. But we’re facing an issue with referral visits.

    Our partner through his analytics counts (for instance) 500 clicks on an outbound link to our site, but we can see only 10% of them as referral traffic within the same timeframe..Any idea – what’s wrong here?


  • Sayf Sharif

    Could be a whole slew of things Anna. Maybe the sites bring in a certain type of visitor that tends to block cookies (though that’s unlikely). Maybe they are tracking events on clicks and their code is wrong? Maybe their code is right, but it’s going to some sort of redirect link page and that changes the visits to direct. Maybe your site is really slow and the people click on their link, but then your site takes forever to load and so they bail before your tracking captures them. Plenty of other ways it could not work on top of those.

  • Paddy

    Hi Guys, I have a quick question, quite recently I seen the source code of a site where the webmaster has used a piece of java script (real time monitoring) after the GA code and just before the I always thought that the GA code was to be the last piece of code right before the

  • Sayf Sharif

    Well the code will work pretty much anywhere on the page that javascript will run. You could have it at the very top below the starting head tag, or at the very bottom above the closing body tag. It’s ok to have code come after or before it, but you’ll get better accuracy the higher the code is up on the page.

  • bob

    iv started a website of my own and iv been trying to use the tracking code i am not quite shur where to put it

  • Sayf Sharif

    Bob, if you have access to the actual code of the page then you’ll want to look for the part of the code that reads and put the tracking code right before/above that line in the file.

    If you have some sort of CMS like WordPress there are plugins you can use to place the tracking code for you.

  • Shri

    Hi Sayf,

    Can “Google Analytics” code create any problem (like throwing credentials popup window), if intranet site doesn’t have access to internet?

    Please reply! Thanks!

  • Sayf Sharif

    No it shouldn’t. If the page has no access to the internet, it would throw some errors in the developer console, but it would be unable to load up the ga.js or dc.js which controls the tracking. Without that it would just error behind the scenes.

  • Shri


  • Where do I paste this tracking code in my wordpress site?
    In widget section I added a text widget in my sidebar and pasted it. But the complete code is visible as text to my visitors. Also google analytics still shows tracking not installed for my website.
    Please help.

  • Sayf Sharif

    Chinks, If you’re using a basic wordpress site I recommend you use the following plugin instead of manually putting the code on your page:


    that will make it easier for you.

    Otherwise you’ll need to modify your theme. Find the header.php file, edit it, and place the code before the closing </head> tag.

  • Hi Sayf, i already have google+ code in my pages, could i reuse that snippet to include both (google+ and google analytics)? thanks, crack!!

  • Sayf Sharif

    Which google+ code? I’m not sure which one you’re referring to.

  • Linda

    Hi, I have my analytics at the bottom of my page and an using the most recent version but have been considering moving it to the top after reading various bits and pieces. However I am unclear now on whether or not this would be a good thing. I have to track a number of outgoing links to other websites. Wherever there is an outgoing link I have the following code:
    onClick=”_gaq.push([‘_trackEvent’, ‘Website Links’, ‘Website Name’]);”
    But as my code is at the bottom I am worried that not all clicks on these links are being tracked and possibly my data is not accurate.
    I am shortly going to be introducing adsense and so am really confused now!
    Should I move it or not?
    I’d really appreciate any help as I’m new to this! Thanks in advance

  • Sayf Sharif

    yes if you’re using the asynchronous code move it to the top of the page put it in the head of the document. It is quite possible that you are not tracking all those links. if that tracking code gets held up by the JavaScript somewhere else on the page it could take seconds before it loads or more and then any clicks on those links won’t be recorded normal visits on this page.

  • Linda

    Thanks Sayf, much appreciated, I have a feeling that not all my links are being tracked so will set about moving it! Appreciate your help 🙂

  • Sarah

    NONE of this info was helpful. I cannot find the “head” section on my googlesite web site, nor am I able to post my analytics ID in the general options where it says to for the enabling of the analytics to work, it won’t save when I hit save. I am at a loss!

  • Sayf Sharif

    Sarah, follow the instructions here:


    “Linking your Google Analytics account and your Google Site

    After you create your new Google Analytics account, you will be directed to you Google Analytics profile screen, where the name of your tracked site should appear, followed by a Google Analytics account number in the format, ‘UA-XXXXXXXX-X.’ Copy this code — known as your Analytics Web Property ID — and go to the site that you want to track with Google Analytics.

    On your site, click the More Actions drop-down menu and select Manage Site.

    Under the Site Settings section, click General.

    Click the box next to Enable Google Analytics for this site and then enter your Analytics Web Property ID in the associated box.

    Click “Save changes.”

    if that doesnt work, or doesnt save, then it sounds like an issue with Google Sites rather than Analytics. Are you sure you are pasting the right thing into that setting? It should be a pattern like UA-1234567-1 . Are you leaving off the UA or trailing number?

  • Hi, I am new to google analytics. Do I need to paste tracking code to every page or simply paste it to my HTML blog template?

  • Sayf Sharif

    It needs to appear on every page. if you have a template that loads onto every page, then putting it there is fine, even preferable.

  • I just popped by to say thanks for putting this in layman terms for people like me! Analytics are even more useful than I could have imagined.

  • We moved our hosting and changed to wordpress, but the old html files are still being tracked. Should the tracking code be removed from these files even though they are no longer on the new domain?

  • Sayf Sharif

    I’m not precisely sure what you’re saying, however your current site you linked has the pages being triple tracked. ie the tracking code is tracking every single pageview as 3 different pageviews. That has to be messing up your data in a huge way.

  • This is a great article Sayf.. Its so annoying when Analytics does not work!

  • Sandy

    Why the heck do you have pictures of fish?

  • I have a lot of pages and i have the google analytics code installed in the footer of my website pages. Great article.

  • i have already past google analytics code on my website but still no report in analytic what to do please help me ?

  • Sayf Sharif

    Sandy, the fish are allegorical.

  • Sayf Sharif


    make sure that you are using the right code, and the right account number, and that the code is inside script tags inside the head of the html.

  • Ri

    The fish may be allegorical, but violent acts of dismembered fish is NOT what I am looking for when finding code snippets. Some of us may be vegan, or practice nonviolence. Save it for your fishing buddies.

  • Sayf Sharif

    You can find out about google authorship at this link: https://plus.google.com/authorship

    It’s not dependent on comments or likes of the article.

  • delivr

    Hi, I’m curious about this quote “It means the asynchronous tracking code averages a 5% improvement in tracking data, with some sites showing 10 and even 20% improvement in their data.” – Can you tell me where these stats come from? I’m trying to convince someone to move their async tracking code and this is just the data I need. Knowing the source would help. Thanks.

    • Sayf Sharif

      I don’t have specific links for it. It’s data that Google has talked about in the past. In general it makes sense, because the code launches earlier on the page, and has less of a chance to get hung up from other scripts. The tests I’ve done in the past generally show improvements in tracking across the board.

  • This is great Wonderful information.. awesome Thanks for sharing.. Interesting post Thanks..

    CMS Development Services India

  • This is great useful information.. Awesome ideas thanks..

    Web Development India

  • PuneetB

    Solid article…As a digital marketer, I’m amazed by so much research going into the positioning of Google Analytics.. I guess it’s time to update ourselves on the asynchronous code..Just had a quick question, what if the code is not used at all? Would that help load the page faster. Could this be advantageous to SEO and to what extent?
    Nonetheless, thanks Sayf for this insight!

    • Sayf Sharif

      asynchronous code generally won’t impede the page. It let’s other code load up and run at the same time, so it won’t decrease load time to remove it. Maybe infinitesimally, but nothing you’d notice. Synchronous code on the other hand could slow down load times, and could theoretically affect your seo.

  • Umer Kayani

    What if we put analytics code in both footer and header? Does it multiple the overall statistics by Google.

    • Sayf Sharif

      Yes. You’d have double tracking and all your numbers would be wrong.

      • Umer Kayani

        Thanks, i removed from footer and now only in heade. And header is good or footer, for placing code.

  • Arun Jadhav

    Using Java with Selenium, how to verify that the Google Tracking Code is a part of tags of a webpage source code ?
    Where would I get the source for the above

  • Kelly Clover

    I don’t understand why Google is making it difficult. They are asking me to insert a Greek snippet somewhere. What’s wrong with simply putting just the UA code on a plugin like All in One SEO that calls for it? Why make it difficult?

    • Sayf Sharif

      You can put it in via a plugin… the problem then just becomes when you want to move past basic pageview tracking. Ultimately I think it’s probably best to use a plugin to insert the Google Tag Manager code, and then create the basic Google Analytics pageview within GTM.

  • I am trying to track a subdirectory of a website in a separate account than the root domain eg. domain.com separate GA and GTM from domain.com/subdirectory/subfolder because it is a franchise and separate from the main account holder, UA-XXXXXX1 is already in the of every page, including subdirectory pages. This means that the subdirectory is showing 2 GA codes (UA-XXXXXX1 & UA-XXXXX2 and I know this causes issues with data. Is it possible to have separate GA and GTM tags on the root domain and subdirectories for different GA and GTM accounts?
    Thanks for any help, I can’t seem to find anything except on your blog.

Contact Us.

Follow Us




We'll get back to you
in ONE business day.
Our Locations
THE FOUNDRY [map] LunaMetrics

24 S. 18th Street
Suite 100

Pittsburgh, PA 15203


4115 N. Ravenswood
Suite 101
Chicago, IL 60613


2100 Manchester Rd.
Building C, Suite 1750
Wheaton, IL 60187