Why does CDATA is commented out under script tags ?

南楼画角 提交于 2019-12-12 14:08:11

问题


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 ? (//)


回答1:


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.



来源:https://stackoverflow.com/questions/16382434/why-does-cdata-is-commented-out-under-script-tags

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!