What is the best way to hide inline Javascript and CSS from downlevel browsers? … I see a few variations on a common theme. Are they all correct, or is one approach better than the other?
<script language="javascript" type="text/javascript">
<!--
// Forces the treeview to adjust to the new size of its container
function resizeTree(DomElementId, NewPaneHeight, NewPaneWidth) {
//do stuff
}
//-->
</script>
vs
<script type="text/javascript">
//<![CDATA[
/* Javascript code here */
//]]>
</script>
vs
<style type="text/css">
/*<![CDATA[*/ CSS stuff here /*]]>*/ </style>
Your first example is the ancient pre-HTML 3.2 method to hide contents of the
scriptelement to browsers that didn’t recognize them. You don’t have to use it anymore. Every current browser (of which IE 6 is the oldest) recognizes these elements and knows that it shouldn’t bluntly show their contents. By the way, thelanguageattribute of thescriptelement has been deprecated long ago, too.Your second and third examples contain CDATA markers, embedded within comments appropriate for the script or style language used. Use those when you embed inline scripts or stylesheets in XHTML documents (and only then). Without those markers a parser would think that ampersands and less-than signs represent special entities or the beginning of tags, respectively. To quote Wikipedia:
This is done the way you show in your second and third examples. The former shows a Javascript example, the latter a CSS snippet.
Also see Comments and CDATA: The mysterious history of script and style in HTML.