Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best place to insert JavaScript within a HTML document [duplicate]

Possible Duplicate:
Where is the best place to put <script> tags in HTML markup?

Where should I put javascript code?

  <-- Here?
</body>
  <-- Here?
</html>
  <-- Here?

I've always used above </body> just wanted to know if this was "the best"

like image 798
obkso Avatar asked Jan 30 '12 19:01

obkso


People also ask

Should I put Scripts 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.

What are two ways to add JavaScript to an HTML file?

There are typically three ways to add JavaScript to a web page: Embedding the JavaScript code between a pair of <script> and </script> tag. Creating an external JavaScript file with the . js extension and then load it within the page through the src attribute of the <script> tag.

Where should I place a script for best page load speed?

Place the script Tag at the Bottom of the Page When you place the script tag at the bottom of the page after the main content, there will be some performance improvement. The content of the page will load and get parsed, as there is no blocking behavior for rendering HTML since you have placed the script in the end.


1 Answers

If the JavaScript needs to be ready to go before the entire page loads, you put it between <head></head>. If the JavaScript needs to be available right before the user encounters something on the page, you can put it prior to the element in the <body></body> (although people hardly do that for code readability). If the JavaScript just does some enhancements or provides tracking information (it's not a necessity), you can put it right before </body>.

like image 129
NightHawk Avatar answered Oct 05 '22 22:10

NightHawk