Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Google unescape their Analytics tracking code?

Just getting off my JavaScript training wheels.

Why does Google choose to unescape the document.write line in Part 1 below?

Why don't they just write it like this? Maybe unescape is required for some older browser compatibility?

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

For reference, the entire Google Analytics tracking code looks like this:

Part 1:

<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>

Part 2:

<script type="text/javascript">
try
{
    var pageTracker = _gat._getTracker("UA-0000000-0");
    pageTracker._trackPageview();
}
catch(err){}
</script>

I understand what the rest of the code does, just curious about the unescape part.

Edit

The bottom line is, unescape is required. Voted to close this question because it is a duplicate (see answer marked correct).

like image 452
Jeff Avatar asked Nov 20 '09 12:11

Jeff


Video Answer


2 Answers

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

Please see: https://stackoverflow.com/questions/1224670/what-is-the-advantage-of-using-unescape-on-document-write-to-load-javascript

like image 101
stpe Avatar answered Sep 22 '22 17:09

stpe


My understanding is when </script> is found even inside the quotes "</script>" the parser wrongly understood that, its reach end of the script, so they cannot do like "</script>"

And Google wants to make sure variables like pageTracker are set before the google-analytics.com/*.js load, so unescaping %3Cscript and %3E%3C/script%3E is only the way for them.

just my 2 cents, sorry If I say wrong.

like image 27
YOU Avatar answered Sep 20 '22 17:09

YOU