Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it wrong to place the <script> tag after the </body> tag?

It won't validate outside of the <body> or <head> tags. It also won't make much difference — unless you're doing DOM manipulations that could break IE before the body element is fully loaded — to putting it just before the closing </body>.

<html>
  ....
  <body>
     ....
     <script type="text/javascript" src="theJs.js"></script>
  </body>
</html>

Yes. Only comments and the end tag for the html element are allowed after the end tag for the body.

Browsers may perform error recovery, but you should never depend on that.


As Andy said, the document will be not valid, but nevertheless the script will still be interpreted. See the snippet from WebKit for example:

void HTMLParser::processCloseTag(Token* t)
{
    // Support for really broken HTML.
    // we never close the body tag, since some stupid web pages close it before
    // the actual end of the doc.
    // let's rely on the end() call to close things.
    if (t->tagName == htmlTag || t->tagName == bodyTag
                              || t->tagName == commentAtom)
        return;
    ...

Internet Explorer doesn't allow this any more (since version 10, I believe) and will ignore such scripts.

Firefox and Chrome still tolerate them, but there are chances that some day they will drop this as non-standard.


Procedurally inserting an "element script" after an "element body" is a "parse error" by the recommended process by W3C. In "Tree Construction" create an error and run "tokenize again" to process that content. So it's like an additional step. Only then can it run the "Script Execution" - see the scheme process.

Anything else is a "parse error". Switch the "insertion mode" to "in body" and reprocess the token.

Technically, by the browser, it's an internal process how they mark and optimize it.