最近我看到了不同的包装内联 JavaScript 的方法:
选项 1:
<script type="text/javascript">//<![CDATA[
...
// ]]></script>
选项 2:
<script>
...
</script>
选项 3:
<script type="text/javascript"><!--
...
//--></script>
选项 4: 以上任何一项的组合?
目前的标准是什么?
最佳答案
HTML5
<script>
alert('Hello world.');
</script>
XHTML
<script type="text/javascript">
//<![CDATA[
alert('Hello world.');
//]]>
</script>
旧浏览器
<script language="javascript"><!--
alert('Hello world.');
//--></script>
要将文档解析为 XML,XHTML 中的 CDATA 部分是必需的。
根据 Douglas Crockford , language
属性已弃用,您可以使用 type
属性代替。在 HTML 中,它是可选的。关于 HTML 评论标签,他是这样说的:
Do not use the
<!-- //-->
hack with scripts. It was intended to prevent scripts from showing up as text on the first generation browsers Netscape 1 and Mosaic. It has not been necessary for many years.<!-- //-->
is supposed to signal an HTML comment. Comments should be ignored, not compiled and executed. Also, HTML comments are not to include--
, so a script that decrements has an HTML error.
因此,如果您正在为今天的网页开发脚本,您将使用 HTML5 方式。
关于javascript - 包装页面 JavaScript 代码的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14188522/