Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 857
Andrew Avatar asked May 14 '10 22:05

Andrew


People also ask

Is it bad to put JavaScript in HTML?

Writing inline JavaScript is one of the many things you learn when you want to tinker with how HTML behaves. However, writing JavaScript straight into your HTML pages is not considered a best practice. In fact, it's considered very 90s by today's coding standards.

Should script be in body HTML?

Always end with a body tag and make sure every single JavaScript part is within the body tag. You can also have links or scripts inside head tags, but it is not recommended unless you are really certain your JavaScript code is too big to have it inline.

Should JavaScript be in body?

The best practice is to put JavaScript <script> tags just before the closing </body> tag rather than in the <head> section of your HTML. The reason for this is that HTML loads from top to bottom. The head loads first, then the body, and then everything inside the body.


1 Answers

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

like image 87
bobince Avatar answered Sep 20 '22 18:09

bobince