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

How wrong is it to place the script tag after the closing tag of the body (</body>). ?

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

This question is related to javascript html

The answer is


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

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

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

I hope I helped somebody.


Yes. But if you do add the code outside it most likely will not be the end of the world since most browsers will fix it, but it is still a bad practice to get into.


Modern browsers will take script tags in the body like so:

<body>
    <script src="scripts/main.js"></script>
</body>

Basically, it means that the script will be loaded once the page has finished, which may be useful in certain cases (namely DOM manipulation). However, I highly recommend you take the same script and put it in the head tag with "defer", as it will give the same effect.

<head>
    <script src="scripts/main.js" defer></script>
</head>

Google actually recommends this in regards to 'CSS Optimization'. They recommend in-lining critical above-fold styles and deferring the rest(css file).

Example:

<html>
  <head>
    <style>
      .blue{color:blue;}
    </style>
    </head>
  <body>
    <div class="blue">
      Hello, world!
    </div>
  </body>
</html>
<noscript><link rel="stylesheet" href="small.css"></noscript>

See: https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery


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;
    ...

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.


IE doesn't allow this anymore (since Version 10, I believe) and will ignore such scripts. FF and Chrome still tolerate them, but there are chances that some day they will drop this as non-standard.