Search code examples
htmlgoogle-pagespeed

Google Pagespeed recommends <script> as direct child element of <html> - valid HTML?


Following Google Pagespeed's recommendations, a colleague just put the <script> tags right between the </body> and </html> closing tags. My immediated assumption was that <html> allows only for <head> and <body> as direct descendants, which I could not exactly verify in the W3C specs:

It says:

Content model: A head element followed by a body element.

To make it clear, what Google pagespeed suggests looks somewhat like this:

<!DOCTYPE html>
<html>
  <head>...</head>
  <body>...</body>
  <script>...</script>
  <script>...</script>
  <script>...</script>
  <script>...</script>
</html>

Does anyone know better or more precisely and can provide a link to a relevant piece of information?


Solution

  • The content model states it pretty clearly: the only children that an html element can legally have is a head element followed by a body element. Not a lone head element, not a lone body element, not a body followed by a head, and certainly not any other element. There are many contexts in which a script element may appear, but it must always be a descendant of either the head element or the body element.

    Google is known for recommending that authors ignore the standards in favor of eking out every last bit of performance, especially when doing so is known not to have any adverse effects or cause any divergent browser behavior. It's up to the author whose guidelines they want to follow.