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

JavascriptHtml

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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

Solution 4 - Javascript

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.

Solution 5 - Javascript

It is valid!

You can use:

<script type="text/javascript">
    //<![CDATA[

    // Some JavaScript code that perfectly validates in the W3C validator

    //]]>
</script>

I don't think you can say if it is a bad practice in general. You have to tell in the case. But sure is that it is good to have all your JavaScript code at the same place. It's a little messy if you have little pieces of JavaScript code all over your HTML file.

Solution 6 - Javascript

I prefer to put references to external scripts into the head, and scripts that start things up and initialize widgets and whatnot into the body.

An issue that's very easy to run into is that a script element in the body cannot access elements that come after it. Also, a related nasty browser compatibility issue is the fact that IE doesn't allow script elements to modify the element they're in. So if you have this:

<div id="foo">
  <script type="text/javascript">
    document.getElementById("foo")... // do something to it
  </script>
</div>

IE is not going to like your page. Old versions of IE used to give very cryptic error messages for this or even blank the entire page, but IE8 seems to give a descriptive error message.

As long as you make sure that your scripts only access DOM that's safe to access, I don't think it's evil to put script elements into the body. In fact, IMHO, putting scripts that initialize widgets after the related elements can be more readable than putting everything in one place (and I believe this might also make them run earlier, which makes stuff jump around less as the page loads).

Solution 7 - Javascript

However, it's also good in that you know the JavaScript code needed for a section of HTML is going to be there for it. Rather than having to assert and build up some inclusion at the top of the file.

So, rather than "if you're going to use this HTML, make sure you import xyz.js" you can just include the HTML and be done with it.

So, it's not necessarily horrible evil. Perhaps not spectacularly awesome, but not utterly terrible either. It kind of depends on the intent.

Solution 8 - Javascript

See the Yahoo UI for best practice: http://developer.yahoo.com/performance/rules.html (JavaScript at the bottom of the page)

Solution 9 - Javascript

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

It's valid, but not a good (or recommended) practice.

> 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?

There's no problem placing a <script> under any other elements (but it should be inside <head> or <body>). There's also no issue in terms of browser compatibility, however, embedding JS scripts on web pages presents serious disadvantages (how/why they are considered bad):

  1. Adds page weight
  2. Difficulty (or probably impossible) for minification
  3. Cannot be migrated or be used for other pages
  4. Cannot be cached (needs to be downloaded every time the page is loaded)
  5. No separation of concerns (harder to maintain)

Solution 10 - Javascript

It's certainly legal; I've seen it on a few pages here on Exforsys for example.

Now this is a tutorial site showing the basics of HTML and JavaScript so in that context it's perfectly understandable. However, I wouldn't like to see it in production code for anything more than a simple statement or two. Without seeing what you've replaced by // Some JavaScript code here I wouldn't like to comment.

There shouldn't be any browser issues with this though.

Solution 11 - Javascript

A few things:

  1. It's completely valid code-wise.
  2. It's completely unrecommended.

Doing this slows down your page load considerably as the JavaScript code must execute before any of the rest of the page can render. If you're doing a lot of work in that JavaScript code, your browser could hang. You should try to (whenever possible) load your JavaScript code dynamically and at the end of your page (preferably before the </body> tag).

Purchase and read High Performance JavaScript. It will change the way you write JavaScript code.

Solution 12 - Javascript

Solution 13 - Javascript

It's one of many, many best practices that's as much about improving performance as it is about improving your approach to programming.

Ultimately in web development, getting the product out matters the most!

Solution 14 - Javascript

I assume that your team is doing this either because they want to insert a script dynamically, or that they are writing a script that will fire at page load.

I wouldn't say there's anything wrong with doing this when ABSOLUTELY NECESSARY, (as long as it's in a CDATA block), but outside of that, I would recommend to your team that they use a script library like Prototype or jQuery, and keep the scripts external to the page. This is usually cleaner, and libraries will sometimes force a bit of cleanliness to the code, which I would bet isn't happening currently.

I also wouldn't run any time-consuming functions in inline script tags, as these happen on page load, and as Jason stated above, could slow the load of the page. All script libraries have neat functions that allow you to do things on load of the page, and will give you the option of when in the page load to fire them, such as after the DOM is loaded.

Solution 15 - Javascript

It is valid to add <script> in body, but Internet Explorer really doesn't likes it. So to be on the safer side, make sure you have your scripts inside the <head> tag.

That was really creating havoc (especially for Internet Explorer) in the project which we are working on.

Solution 16 - Javascript

The oft-stated recommendation that scripts should be kept in the header is to ensure that the script is loaded before it is called. This is only an issue for certain event handlers. For other types of script, it doesn't matter, and for some types (such as document.write), it doesn't make any sense.

Solution 17 - Javascript

If you have an editor that can handle both HTML and JavaScript syntax simultaneously. And if you like to first read a few lines of HTML and then JavaScript cpde...sure. Go for it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrewView Question on Stackoverflow
Solution 1 - JavascriptbobinceView Answer on Stackoverflow
Solution 2 - JavascriptKeltexView Answer on Stackoverflow
Solution 3 - JavascriptPointyView Answer on Stackoverflow
Solution 4 - JavascriptGalView Answer on Stackoverflow
Solution 5 - JavascriptmeoView Answer on Stackoverflow
Solution 6 - JavascriptMatti VirkkunenView Answer on Stackoverflow
Solution 7 - JavascriptWill HartungView Answer on Stackoverflow
Solution 8 - JavascriptJonathan LebrunView Answer on Stackoverflow
Solution 9 - Javascriptuser642922View Answer on Stackoverflow
Solution 10 - JavascriptChrisFView Answer on Stackoverflow
Solution 11 - JavascriptJasonView Answer on Stackoverflow
Solution 12 - JavascriptthSoftView Answer on Stackoverflow
Solution 13 - JavascriptheydenberkView Answer on Stackoverflow
Solution 14 - JavascriptJesseView Answer on Stackoverflow
Solution 15 - JavascriptpaddyView Answer on Stackoverflow
Solution 16 - JavascriptTor HaugenView Answer on Stackoverflow
Solution 17 - JavascriptCheeryView Answer on Stackoverflow