Search code examples
htmlcssgoogle-analyticsteamsite

Implementing Google Analytics without access to the HTML source code


This is likely a very simple question with hopefully a simple answer. I'm using a CMS (TeamSite) and trying to add Google Analytics to a site. The problem is, as the CMS generates the HTML I can't add the Google Analytics code just before the closing </head> tag as Google tells you to. The other method of adding GA to your site is to add some JavaScript before the closing </body> tag. Now I have done this but TeamSite seems to put HTML comments around the JavaScript. Now without sounding like a complete fool, does this mean that the browser will ignore the JavaScript and not execute it? Code is below:

<script type="text/javascript"><!--
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
try{
// --></script>
<script type="text/javascript"><!--
var pageTracker = _gat._getTracker("UA-20657322-12");
pageTracker._trackPageview();
} catch(err) {}
// --></script>

Is there another way for me to add GA to the site without having to take the file from the production server and manually add the script before the closing </head> tag? Any help would be much appreciated.

Thanks


Solution

  • If the HTML comment tags are inserted before and after your and tags, the Javascript will not run. If it is inside the script tag, everything should work fine.

    See for yourself:

    <html>
    <head><title>test</title></head>
    <body>
    
    <script>
    alert('not commented');
    </script>
    
    <!--
    <script>
    alert('outside commented');
    </script>
    -->
    
    <script>
    //<!--
    alert('inside commented');
    //-->
    </script>
    
    </body></html>
    

    The first and third alert will fire, but the second one will not. Like the poster below me mentions, this has to do with backwards compatibility so older browsers that do not support Javascript don't get confused.