你真的需要指定类型属性吗?

2022-01-18 00:00:00 mime-types tags javascript html css

可能重复:
为什么写<脚本类型=“text/javascript”>什么时候服务器设置mime类型?

我不久前阅读了Dive into HTML5,最近又阅读了它的语义章节.我注意到它建议 not 在 scriptstyle 上使用 type="..." 属性,因为:

I read Dive into HTML5 a while back, and read its semantics chapter again just recently. I noted it advises not to use type="..." attributes on script and style, because:

  • MIME 类型应由服务器发送,
  • JS 和 CSS 是默认设置,
  • 浏览器不在乎.

但是,我认为在 script 中包含 type 属性(或者,恐怖,language)仍然是常见的做法>style 标签.假设服务器被正确配置为发送正确的 MIME 类型,除了显式之外,还有其他原因使用这些吗?

However, I see it is still common practice to include type attributes (or, horror, language) on both script and style tags. Assuming the server is properly configured to send the correct MIME types, are there reasons for using these other than being explicit?

编辑:这明确是关于 HTML5,而不是 XHTML.

EDIT: This is explicitly about HTML5, not XHTML.

推荐答案

大多数人习惯于 HTML 4/XHTML 及之前的版本,这些元素需要 type 属性.

Most people are used to HTML 4/XHTML and before, where the type attribute is required for these elements.

关于 HTML 5,这些确实是可选的,并且规范给出了默认值,具体取决于元素.

In regards to HTML 5, these are indeed optional and the spec gives a default, depending on the element.

对于 脚本 标签,默认为 text/javascript:

如果语言不是text/javascript"所描述的,那么 type 属性必须存在

If the language is not that described by "text/javascript", then the type attribute must be present

对于style 标签,默认为 text/css:

type 属性的默认值是text/css".

The default value for the type attribute, which is used if the attribute is absent, is "text/css".

所以,正如你所说,不需要.但是,不能总是依赖浏览器支持和服务器设置 - 明确是一个好主意,因为它可以避免此类问题.

So, not needed, as you stated. However, browser support and server setups can't always be relied on - being explicit is a good idea as it avoids such problems.

当然,并不是所有的浏览器都支持 HTML 5——那些不支持 HTML 5 的浏览器将使用需要该属性的早期版本,并且您的 javascript/css 可能无法在此类浏览器中解析,这意味着您最终没有旧浏览器上的 CSS 或 javascript,当向后兼容的简单解决方案是添加属性时.

And of course, not all browsers out there support HTML 5 - those that don't will use an earlier version where the attribute is required and your javascript/css might not get parsed in such browsers, meaning you end up with no CSS or javascript on older browsers, when a simple solution for backwards compatibility is to add the attribute.

相关文章