views:

689

answers:

3

The code that you have to add to track a web page with google analytics looks like:

<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"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-XXXXX");
pageTracker._trackPageview();
} catch(err) {}</script>

What's the advantage of doing these line:

document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

versus these line:

document.write("<script src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'><\/script>");

I wrote a code that does something similar (load javascript "via" document write) but does not use unescape and I am wondering if I should follow the google-analytics example.

A: 

Well, one advantage is that it means you don't have to worry about quotes within the script being loaded interfering with quotes in your script that's doing the loading (since the ones in the loaded script can be escaped).

Amber
+7  A: 

It means the code will work in XML / XHTML and HTML without having to mess with CDATA

Greg
Would it be ok to use document.write("\x3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'\x3E\x3C/script\x3E");
TJ
A: 

It means that you can devote a your page, to those who do have JS turned on. I.e. only those with JS turned-on to call the function. For those who do not, you can embed in the same .html page a searate piece of code using the "" tags.

mana
means that you can devote a your page, to those who do have JS turned on. I.e. only those with JS turned-on to call the function. For those who do not, you can embed in the same .html page a searate piece of code using the "no script" tags.
mana