I was reading this question and I have a related question :
This guy here said that :
It is used in script tags to avoid parsing < and &. In HTML, this is not needed, because in HTML, script is already #CDATA.
Question #1
If SCRIPT is already #CDATA : why does it renderd (under script tag) still as CDATA ?
<script type="text/javascript">
// <![CDATA[
// ]]>
</script>
Question #2
And why is it as a comment ? (//
)
XHTML is supposed to be served as XML by using media type application/xhtml+xml
. In HTML5, the markup is only XHTML if it is served with an XML media type. When served like this, the contents of script elements are not CDATA.
So to get the XML parser to treat the script contents as CDATA, they can be wrapped in <![CDATA[ ]]>
.
While few people have historically served markup as application/xhtml+xml
, many have validated their pages as if it was XHTML. The XHTML validator equally expects that the script contents are not ordinarily CDATA, and so will typically reject tags and other scraps of markup embedded in the JavaScript, unless they are escaped with <![CDATA[ ]]>
Having validated their pages as XHTML, they'd then serve their pages with a text/html
media type to browsers, which meant that the browser treats the markup as HTML, not XHTML. In this case, the HTML parser is used, which does treat the script contents as CDATA automatically, so the <![CDATA[
and ]]>
. become part of the script to be run by the JavaScript engine. Therefore, to hide those strings from the JavaScript engine, they are preceded with //
on the same line, which means that the JavaScript engine thinks the lines are comments.
Finally, some people serve the same markup as both application/xhtml+xml
and text/html
, switching based on the information found in the HTTP request message. For the same reasons as above, to get the script contents to be processed correctly in both modes, the //<![CDATA[
and //]]>
pattern is a very effective technique.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With