54qyc
V2EX  ›  HTML

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

  •  1
     
  •   54qyc · Aug 14, 2023 · 4588 views
    This topic created in 1177 days ago, the information mentioned may be changed or developed.

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

    9 replies  •  2023-09-04 20:36:37 +08:00
    rrfeng
    rrfeng
    Aug 14, 2023
    1
    content-type 指代 HTML 协议的 payload 的类型与编码
    -----
    content-type 指代 HTTP 协议的 payload 的类型与编码
    i8k
    i8k
    Aug 14, 2023
    2
    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
    JinTianYi456
    Aug 14, 2023
    3
    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
    54qyc
    OP
    Aug 14, 2023
    4
    @i8k 这个问题和我的问题不是一个问题
    54qyc
    54qyc
    OP
    Aug 14, 2023
    5
    @rrfeng 请看内容,假设 content-type 中 charset 是 A , 那么浏览器会以 A 来解码这个 html document 吗?当浏览器解析 document 匹配到 meta 标签时,如果 meta 标签里的 charset 是 B ,浏览器接下来来会如何解析这个 document ?
    54qyc
    54qyc
    OP
    Aug 14, 2023
    6
    @JinTianYi456 这个我也搜到过,本地解析的话, 浏览器不得线以某种编码解码 html 文件才能读取到 meta 这个标记吗?读取之后再切换编码吗?
    JinTianYi456
    JinTianYi456
    Aug 14, 2023
    7
    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
    rrfeng
    Aug 15, 2023
    8
    我理解这其实是两个不同程序的问题:
    网络层告诉渲染器这个文件是啥
    html 里的 meta 是告诉渲染器这个文件内容是啥

    类似于:
    以太网链路层有校验了,为啥 tcp 还要自己加校验?
    chnwillliu
    chnwillliu
    Sep 4, 2023 via Android
    9
    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
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2922 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 12:33 · PVG 20:33 · LAX 04:33 · JFK 07:33
    ♥ Do have faith in what you're doing.