开发者

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 (TeamS开发者_C百科ite) 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


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.


In a script block HTML comments are treated slightly differently. In a script block single line comment.

The reason for this is so that in really old browsers that don't know about script tags you could use this sort of markup and if it didn't understand script tags it would not render the javascript to page (because it thinks its in a comment) and if it does understand script tags it will just treat teh opening one as a single line comment and then the closing tag is normally marked as a commetn using the //.

So in summary these comment tags shouldn't be causing you a problem that I can see.

Is the script not being run on your page are are you just uncertain where your issue lies? Sticking an "alert('test');" into that block should allow you to confirm that it is being run.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜