当服务器设置了 mime 类型时,为什么要写 < script type = “ text/javascript”> ?

我的理解是哑剧类型是由 Web 服务器设置的。为什么要添加 type="text/javascripttype="text/css"属性?这不是一个无用且被忽略的属性吗?

119916 次浏览

因为,至少在 HTML 4.01和 XHTML 1(.1)中,<script>元素的 type属性是 需要

HTML 5中,不再需要 type

实际上,虽然您应该在 HTML 源代码中使用 text/javascript,但是许多服务器将发送带有 Content-type: application/javascript的文件。在 RFC 4329中阅读有关这些 MIME 类型的更多信息。

请注意 RFC 4329(标记 text/javascript已过时并建议使用 application/javascript)与现实中一些浏览器对包含 type="application/javascript"<script>元素(在 HTML 源代码中,而不是发送文件的 HTTP Content-type 头部)的不同之处。最近,WHATWG 邮件列表上有一个关于这个差异的讨论(HTML 5的 type默认为 text/javascript) ,阅读主题 你会考虑 RFC 4329吗?的这些消息

道格拉斯·克罗克福特说:

type="text/javascript"

此属性是可选的 Netscape 2,默认编程 所有浏览器的语言 在 XHTML 中,此属性 在 HTML 中, 最好把它放在外面 浏览器知道该怎么做。

他还表示:

W3C 没有采用 language 属性,倾向于使用 type 属性,该属性采用 MIME 类型。 不幸的是,MIME 类型不是 标准化,所以有时候 "text/javascript""application/ecmascript"还是什么的 幸运的是,所有的浏览器都会 始终选择 JavaScript 作为 默认的编程语言,所以它是 总是最好简单地写 <script>。 它是最小的,它工作在 大多数浏览器。

仅仅为了娱乐目的,我尝试了以下五个脚本

  <script type="application/ecmascript">alert("1");</script>
<script type="text/javascript">alert("2");</script>
<script type="baloney">alert("3");</script>
<script type="">alert("4");</script>
<script >alert("5");</script>

在 Chrome 浏览器上,除了脚本3(type="baloney")以外,其他都可以正常工作。IE8没有运行脚本1(type="application/ecmascript")或脚本3。基于我的两个浏览器的非扩展示例,看起来您可以安全地忽略 type属性,但是如果您使用它,您最好使用一个合法的(依赖于浏览器的)值。

它允许浏览器在请求脚本或样式表之前确定是否能够处理脚本/样式语言(或者,在嵌入式脚本/样式的情况下,确定正在使用哪种语言)。

如果浏览器领域的语言之间存在更多的竞争,那么这一点就会更加重要,但是 VBScript 从未超越 IE,PerlScript 从未超越 IE 特定的插件,而 JSSS 从一开始就是垃圾。

HTML5的草案使该属性成为可选的。

Boris Zbarsky (Mozilla)可能比任何人都更了解 Gecko 的内部构造,他在 http://lists.w3.org/Archives/Public/public-html/2009Apr/0195.html上提供了下面重复的伪代码来描述基于 Gecko 的浏览器的功能:

if (@type not set or empty) {
if (@language not set or empty) {
// Treat as default script language; what this is depends on the
// content-script-type HTTP header or equivalent META tag
} else {
if (@language is one of "javascript", "livescript", "mocha",
"javascript1.0", "javascript1.1",
"javascript1.2", "javascript1.3",
"javascript1.4", "javascript1.5",
"javascript1.6", "javascript1.7",
"javascript1.8") {
// Treat as javascript
} else {
// Treat as unknown script language; do not execute
}
}
} else {
if (@type is one of "text/javascript", "text/ecmascript",
"application/javascript",
"application/ecmascript",
"application/x-javascript") {
// Treat as javascript
} else {
// Treat as specified (e.g. if pyxpcom is installed and
// python script is allowed in this context and the type
// is one that the python runtime claims to handle, use that).
// If we don't have a runtime for this type, do not execute.
}
}