Is it bad practice to embed JavaScript into the body of HTML?

A team that I am working on has gotten into the habit of using <script> tags in random places in the body of our HTML pages. For example:

<html>
    <head></head>
    <body>
        <div id="some-div">
            <script type="text/javascript">//some javascript here</script>
        </div>
    </body>
</html>

I had not seen this before. It seems to work in the few browsers that I've tested. But as far as I know, it's not valid to put script tags in places like this.

Am I wrong? How bad is it that we are putting script tags within div tags like this? Are there any browser compatibility issues I should be aware of?


Solution 1:

It's perfectly valid.

You wouldn't want to put great big blocks of code mixed up in the markup there (better to use external scripts), but it can be useful to:

  • add extra binding information for progressive-enhancement (where that data is difficult to fit into a classname or other approach to hiding extended information in attributes); or

  • where it's necessary to kick off a scripted enhancement as quickly as possible (rather than waiting for window-load/document-ready). An example of this would be autofocus, which can irritate if fired too late.

You may be thinking of <style> elements, which aren't allowed in <body> (although most browsers allow it nonetheless).

Solution 2:

Actually, it's quite common. For example Google's analytics tracking code uses just this syntax:

<script type="text/javascript">
  var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
  document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>

If it's good enough for Google...

Solution 3:

It is valid and, depending on your server-side framework and the nature of the code, sometimes very difficult to avoid.

Solution 4:

As several people mentioned, it's valid, it works, and it is widely used.

Best practices as far as semantics recommend (or at least used to recommend) is placing script tags inside of the header.

More modern best practices which take performance into account recommend placing script tags (external and inline) at the bottom right before the body tag, to allow the markup to render completely before any JavaScript code executes.

For easier to understand and maintainable code, "unobtrusive JavaScript" is recommended, where the code is in an external file and binds events to the DOM (Google unobtrusive JavaScript).

One case where it's useful to have JavaScript inline is to initialize variables with values that only exists server side, which will then later be used by the external JavaScript code.