V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Dive into HTML5
http://diveintohtml5.org/
54qyc
V2EX  ›  HTML

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

  •  1
     
  •   54qyc · 257 天前 · 914 次点击
    这是一个创建于 257 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

    类似于:
    以太网链路层有校验了,为啥 tcp 还要自己加校验?
    chnwillliu
        9
    chnwillliu  
       236 天前 via Android
    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
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3946 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 10:19 · PVG 18:19 · LAX 03:19 · JFK 06:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.