views:

38

answers:

1

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>
+3  A: 

Your first example is the ancient pre-HTML 3.2 method to hide contents of the script element 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, the language attribute of the script element 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:

Since it is useful to be able to use less-than signs (<) and ampersands (&) in web page scripts, and to a lesser extent styles, without having to remember to escape them, it is common to use CDATA markers around the text of inline <script> and <style> elements in XHTML documents. But so that the document can also be parsed by HTML parsers, which do not recognise the CDATA markers, the CDATA markers are usually commented-out

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.

Marcel Korpel
Does any of this change when dealing with CSS embedded within an email message? e.g. a blackberry client, or other device
MakerOfThings7
@Maker – I really doubt it, as we're still dealing with XHTML. But, if possible, I would send an HTML email as HTML (with HTML 5 Doctype) and not as XHTML, thereby circumventing this whole issue (or rather, send email as plain text, but that's more a personal preference).
Marcel Korpel