开发者

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>
开发者_Go百科

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


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


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.


Writing directly into the document without using the '<' or '>' characters means that you don't have to escape them in document formats which interpret these literally. Otherwise, the correct interpretation is that the <script> tags begin inside of the string, which is not what's desired.

Also, note that there's an error in your proposed alternative code (you missed a quote mark after the end of the src attribute).


I think that:

document.wrIte('<script src="'"

will fail HTML Validation as well. Interestingly, it also breaks the Preview on this comment box :)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜