Javascript HTML Script 标签:类型或语言(或两者都省略)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2267476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML Script tag: type or language (or omit both)?
提问by Ricket
<script type="text/javascript">
/* ... */
</script>
vs.
对比
<script language="Javascript">
/* ... */
</script>
Which should be used and why?
应该使用哪个,为什么?
Or, the third alternative: omitting either of these, such as the example code in jQuery's API reference:
或者,第三种选择:省略其中任何一个,例如 jQuery 的 API 参考中的示例代码:
<script src="http://code.jquery.com/jquery-latest.js"></script>
回答by Matchu
The languageattribute has been deprecated for a long time, and should not be used.
该language属性已被弃用很长时间,不应使用。
When W3C was working on HTML5, they discovered all browsers have "text/javascript" as the default script type, so they standardized it to be the default value. Hence, you don't need typeeither.
W3C 在开发 HTML5 时,发现所有浏览器都将“text/javascript”作为默认脚本type,因此将其标准化为默认值。因此,您也不需要type。
For pages in XHTML 1.0 or HTML 4.01 omitting typeis considered invalid. Try validatingthe following:
对于 XHTML 1.0 或 HTML 4.01 中的页面,省略type被认为是无效的。尝试验证以下内容:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://example.com/test.js"></script>
</head>
<body/>
</html>
You will be informed of the following error:
您将被告知以下错误:
Line 4, Column 41: required attribute "type" not specified
第 4 行,第 41 列:未指定必需属性“类型”
So if you're a fan of standards, use it. It should have no practical effect, but, when in doubt, may as well go by the spec.
因此,如果您喜欢标准,请使用它。它应该没有实际效果,但是,如果有疑问,也可以按照规范进行。
回答by Ms2ger
HTML4/XHTML1 requires
HTML4/XHTML1 需要
<script type="...">...</script>
HTML5 faces the fact that there is only one scripting language on the web, and allows
HTML5 面临网络上只有一种脚本语言的事实,并允许
<script>...</script>
The latter works in any browser that supports scripting (NN2+).
后者适用于任何支持脚本 (NN2+) 的浏览器。
回答by JasCav
The typeattribute is used to define the MIME type within the HTML document. Depending on what DOCTYPE you use, the type value is required in order to validate the HTML document.
该类型属性被用来定义在HTML文档中的MIME类型。根据您使用的 DOCTYPE,需要类型值才能验证 HTML 文档。
The language attribute lets the browser know what language you are using (Javascript vs. VBScript) but is not necessarily essential and, IIRC, has been deprecated.
语言属性让浏览器知道您使用的是什么语言(Javascript 与 VBScript),但它不一定是必需的,而且 IIRC 已被弃用。

