Forum Moderators: open
<script type="text/javascript">
//<![CDATA[
document.write('<scr'+'ipt src="http://crazyegg.com/pages/scripts/8956.js?'+(new Date()).getTime()+'" type="text/javascript"></scr'+'ipt>');
//]]>
</script>
I'm not an expert but I feel that this script doesn't follow the best practices, could someone please fix it for me? and for them too since I'll notify them.
[edited by: DrDoc at 5:02 am (utc) on Sep. 29, 2006]
<script type="text/javascript">
//<![CDATA[
document.write('<scr'+'ipt src="http://crazyegg.com/pages/scripts/8956.js?'+(new Date()).getTime()+'" type="text/javascript"></scr'+'ipt>');
//]]>
</script>
The problem is that they want all pages to validate and they want to get a timestamp on the URI that they are calling.
Breaking down what they did and why they did it.
//<![CDATA[
This should be the first really weird thing that stands out. To a parser that might try to validate the page it might look like they are trying to put a <script> tag inside a <script> tag, and they are so for anyone using XSLT translations on their pages they need the parser to skip all of this so they are putting everything inside a CDATA element so that the parser will skip it.
document.write('<scr'+'ipt
This is probably the next thing that looks funny to you. But they are trying to write a link to a javascript source from javascript so they want the outer <script> tag to generate the second without interpreting it as bad html so they split the name.
src="http://crazyegg.com/pages/scripts/8956.js?'+(new Date()).getTime()+'" type="text/javascript"></scr'+'ipt>');
Now we get to the purpose of all of this stuff. they are using the outer javascript to write a timestamp on the URI of the inner script then write that to the page so that the browser will call for it.
They also have to break up the closing </script> tag so that the browser won't close the outer <script> before they finish their document.write command.
//]]>
This is the close of the CDATA element commented out of javascript.
So it might look like they are being all non compliant non standard and inefficient but this is actually the only way to do this with pure javascript and be interpretted by the most web server environments while still being compliant.