Came across an interesting problem today, whilst creating a template for a new website, I noticed that the Google analytics tracking code was failing XHTML validation.
<script type=”text/javascript” language=”javascript”>
if(typeof(urchinTracker)!=’function’)document.write(’<sc’+'ript src=”‘+’http’+(document.location.protocol==’https:’?’s://ssl’:'://www’)+’.google-analytics.com/urchin.js’+'”><’+'/sc’+'ript>’)
</script>
I later discovered that wrapping the script in CDATA tags allowed the script to parse and validate – happy days!
<script type=”text/javascript” language=”javascript”>
//<![CDATA[if(typeof(urchinTracker)!='function')document.write('<sc'+'ript src="'+'http'+(document.location.protocol=='https:'?'s://ssl':'://www')+'.google-analytics.com/urchin.js'+'"><'+'/sc'+'ript>')//]]>
</script>
Tags: code, google, tracking, validation












Wrapping it in comments also work ‘<!–’ and ‘// –>’
Does the page have an < ?xml tag at the top? If so then it's an *actual* XML document, (rather than just XHTML which isn't *necessarily* XML despite what the name might suggest), and therefore the script will need to go in a block. If it’s just an XHTML or HTML document then you can get away without the need for CDATA. I think.