I’m wondering how to declare JavaScript code within a CDATA section so that it is compatible with XHTML. Which method is correct/recommended?
Method 1:
<script type="text/javascript">
// <![CDATA[
CODE
// ]]>
</script>
Method 2:
<script type="text/javascript">
/* <![CDATA[ */
CODE
/* ]]> */
</script>
Is the second one also suitable for inline CSS?
And, is it possible/does it make sense to add some encoding declaration here like
<script type="text/javascript" charset="utf-8">
...
<style type="text/css" media="screen" charset="utf-8">
...
or
<script type="text/javascript">
@charset "utf-8";
...
<style type="text/css" media="screen">
@charset "utf-8";
...
Either are equally good.
Yes.
However, you only need to worry about putting script and style blocks in a
<![CDATA[section when you want to include the characters<or&in the block. You’ll almost never use them in CSS.You might use them in JavaScript, but it’s generally better to avoid the issue by putting any significant amount of code in external scripts where it belongs. Inline script blocks tend to be better for putting data and script-invocation calls in, which rarely need to use
<or&(except in string literal values, in which case there’s an argument for encoding them to eg.\x3Cinstead).No. The
charset="..."attribute only has any meaning for external files (and doesn’t exist on<style>since that is never an external file). Internal content has already been decoded from bytes to characters at the same time as the rest of the containing document, socharsetis meaningless by this point.In any case, not all browsers pay any attention to the
<script charset>attribute, so you have to make the encoding of scripts match the encoding of the page that includes them. Which makescharset="..."quite redundant.@charset "utf-8";is OK in external style sheets, but you almost never need non-ASCII characters in stylesheets so it’s unusual to see it.@charsetis not valid in JavaScript.