Does my HTML5 doctype have to be on the VERY first line?

后端 未结 6 1149
心在旅途
心在旅途 2020-12-18 18:32

I\'ve always wondered whether whitespace before a DOCTYPE matters, but I can\'t seem to find any definitive information on the web. People say not to do it,

相关标签:
6条回答
  • 2020-12-18 18:33

    Yes! comments and spaces may come first.

    Here's the relevant section from the official HTML Specification

    0 讨论(0)
  • 2020-12-18 18:38

    To maximize the odds of avoiding Quirks Mode, put the doctype declaration at the very start of the HTML document. You won’t find any official statement on this, since Quirks Mode is about violating standards and about actual browser behavior. It is part of the very idea of Quirks Mode that it is largely undocumented; authors are not supposed to trust on it. It’s meant to make legacy pages behave tolerably (as they used to), not something that you should use for new pages.

    Modern browsers generally allow an empty line before the doctype, or a comment, or an XML declaration, without going to Quirks Mode. But just don’t put anything there, unless you have a compelling reason to do so.

    0 讨论(0)
  • 2020-12-18 18:39

    No, the Doctype doesn't have to be the first line of the file but it does have to come before the <html> tag. That is the only limit you have, so your first method to do it is fine.

    The declaration must be the very first thing in your HTML document, before the tag.

    Gotten from: w3 schools (doctypes)

    0 讨论(0)
  • 2020-12-18 18:41

    There are occasional browsers that have problems with whitespace before the doctype -- the classic example was IE6, which was said to go into quirks mode at the sight of it. Turns out that this is only true for some very specific types of whitespace (non-breakable spaces, &nbsp; for example). That said, IE6 compatibility is not high on most peoples' priority lists.

    0 讨论(0)
  • 2020-12-18 18:43

    Actually, the practical advice is to limit initial text that includes a <meta charset="UTF-8"> statement to 1024 bytes. This is due to the need of some browsers to use a limited prescan to determine the character encoding quickly if a character encoding header is missing.

    See W3C and Sivonen for details.

    0 讨论(0)
  • 2020-12-18 18:59

    Note that the HTML specification linked to by Ray is wrong. While whitespace is allowed before the DOCTYPE, the specification says that also comments may come before the DOCTYPE. But that does not work in Internet Explorer 9 and older.

    0 讨论(0)
提交回复
热议问题