Is it wrong to place the <script> tag after the </body> tag?
Only comments and the end tag for the html element are allowed after the end tag for the body.
You can confirm this with the specification or a validator.
Browsers may perform error recovery, and the HTML specification even describes how to recover in that situation, but you should never depend on that.
It is also worth noting that the usual reason for putting the script element at the end is to ensure that elements the script may try to access via the DOM exist before the script runs.
With the arrival of the defer
attribute we can place the script
in the head and still get that benefit while also having the JS be downloaded by the browser in parallel with the HTML for better performance.
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;
...
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>