html document 的字符编码问题: content-type 与 meta charset 的区别?

272 天前
 54qyc

已知:content-type 指代 HTML 协议的 payload 的类型与编码, 当 payload 是 html document 时,假设 content-type 中 charset 是 A , 那么浏览器会以 A 来解码这个 html document 吗?当浏览器解析 document 匹配到 meta 标签时,如果 meta 标签里的 charset 是 B ,浏览器接下来来会如何解析这个 document ?会换用 B 去解码接下来的字符吗? meta charset 这种设计的应用场景是哪里呢?

945 次点击
所在节点    HTML
9 条回复
rrfeng
272 天前
content-type 指代 HTML 协议的 payload 的类型与编码
-----
content-type 指代 HTTP 协议的 payload 的类型与编码
i8k
272 天前
In HTML5, they are equivalent. Use the shorter one, as it is easier to remember and type. Browser support is fine since it was designed for backwards compatibility.

https://stackoverflow.com/questions/4696499/meta-charset-utf-8-vs-meta-http-equiv-content-type
JinTianYi456
272 天前
Do both. The header takes precedence, but if the HTML page is accessed locally, there are no HTTP-headers, so you want to have <meta charset="..."> as a safety mechanism.
54qyc
272 天前
@i8k 这个问题和我的问题不是一个问题
54qyc
272 天前
@rrfeng 请看内容,假设 content-type 中 charset 是 A , 那么浏览器会以 A 来解码这个 html document 吗?当浏览器解析 document 匹配到 meta 标签时,如果 meta 标签里的 charset 是 B ,浏览器接下来来会如何解析这个 document ?
54qyc
272 天前
@JinTianYi456 这个我也搜到过,本地解析的话, 浏览器不得线以某种编码解码 html 文件才能读取到 meta 这个标记吗?读取之后再切换编码吗?
JinTianYi456
272 天前
This attribute declares the document's character encoding. If the attribute is present, its value must be an ASCII case-insensitive match for the string "utf-8", because UTF-8 is the only valid encoding for HTML5 documents. <meta> elements which declare a character encoding must be located entirely within the first 1024 bytes of the document.
rrfeng
271 天前
我理解这其实是两个不同程序的问题:
网络层告诉渲染器这个文件是啥
html 里的 meta 是告诉渲染器这个文件内容是啥

类似于:
以太网链路层有校验了,为啥 tcp 还要自己加校验?
chnwillliu
251 天前
Http header 优先级高,其次是 meta http-equiv 然后是 meta charset

应用场景是如果 http header 没有声明 charset 或者压根就不存在 http header 比如打开本地 html 文件。

HTML5 还定义了更多的各种 encoding sniff 算法,有可能会存在假定编码先解析。

https://stackoverflow.com/questions/26030572/what-is-the-difference-between-the-charset-in-http-header-and-html-meta

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/965233

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX