Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why put JavaScript in head

If it is perfectly acceptable to put JavaScript right before </body> what is a good reason to keep it in the <head>?

Based on the question JavaScript in <head> or just before </body>? many answers state that the page will load faster if you put it right before the </body> tag.

However I don't see any sound arguments on why it should be kept in the <head>. I'm asking because I am not a very strong JavaScript developer and from everything I've read and seen, the standard is to keep most JavaScript code and external references in the the <head>.

like image 475
Danny Avatar asked Nov 23 '11 21:11

Danny


People also ask

Is it better to put JavaScript in head or 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.

Does JavaScript need to be in head?

No, it can be anywhere.

Should you put script in head?

Put your functions in the head section, this way they are all in one place, and they do not interfere with page content. If your is not placed inside a function, or if your script writes page content, it should be placed in the body section. It is a good idea to place scripts at the bottom of the <body> element.

Why do we write JavaScript code in body and head tag?

Generally javascript code will function in the head before code in the body. The head section is usually used to contain information about the page that you dont neccessarily see like the meta keywords meta description or title of a page. You would also link to any external files like .


1 Answers

Anything in the head must be completed before the body is loaded, so it is generally a bad idea to put javascript in there. If you need something while the body is loading, or want to expedite some ajax, then it would be appropriate to put it in the head.

like image 197
regality Avatar answered Oct 08 '22 10:10

regality