Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does javascript have to be in the head tags?

Tags:

javascript

I believe javascript can be anywhere (almost), but I almost always see it in between <head></head>. I am using jquery and wanted to know if it has to be in the head tags for some reason or if will break something if I move it. Thank you.

EDIT: Why is it almost always in the head tags?

like image 295
johnny Avatar asked Jul 31 '09 15:07

johnny


People also ask

Where should I put JavaScript in HTML?

The script tag should always be used before the body close or at the bottom in HTML file. The Page will load with HTML and CSS and later JavaScript will load.

Should scripts go in head or body?

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.


2 Answers

No, it can be anywhere. In fact, it’s sometimes a good idea to put it at the bottom of the document. For an explanation why, see http://developer.yahoo.com/performance/rules.html#js_bottom.

like image 181
Nate Avatar answered Oct 11 '22 22:10

Nate


JavaScript is executed wherever it is found in the document. If you place inline JavaScript in the body, it will be executed when the browser comes to it. If you're using $(document).ready(...) to execute things, then the positioning shouldn't matter. Otherwise, you may find corner cases where it matters. In general, it does not matter. Scripts end up in the head tag mostly out of tradition.

like image 36
John Calsbeek Avatar answered Oct 11 '22 22:10

John Calsbeek