Should I use <![CDATA[…]]> in HTML5?

前端 未结 4 670
傲寒
傲寒 2020-12-12 19:17

I\'m pretty sure sections can be used in XHTML5, but what about HTML5?

相关标签:
4条回答
  • 2020-12-12 19:53

    The spec seems to clear up this issue. script and style tags are considered to be "raw text elements." CDATA is not needed or allowed for them. CDATA is only used with "foreign content" - i.e. MathML and SVG. Note that there are some restrictions to what can go in the script tag -- basically you can't put something like var x = '</script>' in there because it will close the tag and needs to be split like pst noted in his answer. http://www.w3.org/TR/html5/syntax.html#cdata-rcdata-restrictions

    0 讨论(0)
  • 2020-12-12 19:55

    Perhaps see: http://wiki.whatwg.org/wiki/HTML_vs._XHTML

    <![CDATA[...]]> is a a bogus comment.

    In HTML, <script> is already protected -- this is why sometimes it must be written as a = "<" + "/script>", to avoid confusing the browser. Note that the code is valid outside a CDATA in HTML.

    0 讨论(0)
  • 2020-12-12 19:58

    From the same page @pst linked to:

    Element-specific parsing for script and style tags, Guidance for XHTML-HTML compatibility: "The following code with escaping can ensure script and style elements will work in both XHTML and HTML, including older browsers."

    Maximum backwards compatibility:

    <script type="text/javascript"><!--//--><![CDATA[//><!--
        ...
    //--><!]]></script>
    

    Simpler version, sort of incompatible with "much older browsers":

    <script>//<![CDATA[
       ...
    //]]></script>
    

    So, CDATA can be used in HTML5, and it's recommended in the Guidance for XHTML-HTML compatibility. This useful for polyglot HTML/XML/XHTML pages, which are created and parsed as XML during development, but served as HTML5 for better cross-browser compatibility. Polyglot pages has their benefits, and I've used this myself, as it's much easier to debug XML/XHTML5. Google Chrome, for example, will throw an error for invalid XML/XHTML5 (including for example character escaping), whereas the same page served as HTML5 will "just work" aka "probably work".

    0 讨论(0)
  • 2020-12-12 20:13

    The CDATA structure isn't really for HTML at all, it's for XML.

    People sometimes use them in HTML inside script tags because it removes the need for them to escape certain special characters. It’s by no means a requirement, though (for either HTML 4 or 5).

    Edit: This is where we open that really mouldy old can of worms from 2002 over whether you're sending XHTML as text/html or as application/xhtml+xml like you’re “supposed” to :-)

    0 讨论(0)
提交回复
热议问题