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

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.


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,   for example). That said, IE6 compatibility is not high on most peoples' priority lists.


Yes! comments and spaces may come first.

Here's the relevant section from the official HTML Specification


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.