Which is better: <script type="text/javascript">...</script> or <script>...</script>

Which is better or more convenient to use:

<script type="text/javascript">...</script>

or

<script>...</script>
164036 次浏览

两者都可以工作,但是 xhtml 标准也要求您指定 type:

<script type="text/javascript">..</script>


<!ELEMENT SCRIPT - - %Script;          -- script statements -->
<!ATTLIST SCRIPT
charset     %Charset;      #IMPLIED  -- char encoding of linked resource --
type        %ContentType;  #REQUIRED -- content type of script language --
src         %URI;          #IMPLIED  -- URI for an external script --
defer       (defer)        #IMPLIED  -- UA may defer execution of script --
>

Type = content-type [ CI ] 此属性指定元素的脚本语言 contents and overrides the default 脚本语言剧本 语言指定为内容 type (e.g., "text/javascript"). Authors must supply a value for this 没有默认值 对于这个属性。

Notices the emphasis above.

Http://www.w3.org/tr/html4/interact/scripts.html

Note: As of HTML5, the type attribute is not required and is default.

除非使用 html5,否则需要使用 <script type="text/javascript"> </script>。在这种情况下,鼓励您选择 <script> ... </script>(因为 type 属性在默认情况下指定为该值)

因为它的正确方式和兼容所有浏览器

您真的需要 type 属性吗?如果你使用 HTML5,不。除此之外,是的。HTML 4.01和 XHTML 1.0根据需要指定 type属性,而 HTML5将其作为可选属性,默认为 text/javascript。HTML5现在得到了广泛的实现,所以如果您使用 HTML5 doctype,<script>...</script>是有效的,也是一个不错的选择。

至于 type 属性应该包含哪些内容,2006年注册的 MIME 类型 application/javascript旨在取代 text/javascript,并得到所有主流浏览器(包括 Internet Explorer 9)的当前版本的支持。引自 相关的 RFC:

这个文档因此定义了 text/javascript 和 text/ecmascript,但是将它们标记为“过时的”。不鼓励使用上面部分列出的实验性和未注册的媒体类型。媒体类型,

  * application/javascript
* application/ecmascript

which are also defined in this document, are intended for common use and should be used instead.

但是,包含版本8的 IE 不会在 <script>元素中执行脚本,type属性为 application/javascriptapplication/ecmascript,所以如果需要支持旧的 IE,那么就只能使用 text/javascript了。

这就是我们所需要的:

<!doctype html>
<script src="/path.js"></script>

使用最新的 Firefox,我必须使用:

<script type="text/javascript">...</script>

否则脚本可能无法正常运行。

对于 HTML5,<syntax>...</syntax>使用起来更好更方便。如果您使用的是 HTML5,则无需显式提及 type = "text/javascript",因为 类型属性默认设置为 "text/javascript",所以它是完全可选的。