Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to place JavaScript functions: <head>? <body>? or, after </html>?

Tags:

javascript

I'm confused about where to place JavaScript functions:

When should they be put within the head When inline within the body And, when after the closing html tag?

thanks

like image 736
Doug Null Avatar asked Mar 01 '12 16:03

Doug Null


People also ask

Where do you put JavaScript head or body?

JavaScript in head: A JavaScript function is placed inside the head section of an HTML page and the function is invoked when a button is clicked. JavaScript in body: A JavaScript function is placed inside the body section of an HTML page and the function is invoked when a button is clicked.

Where do I put JavaScript function in HTML?

The <script> Tag In HTML, JavaScript code is inserted between <script> and </script> tags.

Does body or head come first in HTML?

The HTML document starts after the doctype declaration and is encompassed in opening and closing html tags. Inside the html tags come the head element and, afterwards, the body element. Although there are many more HTML elements, the aforementioned elements are sufficient to build a (basic) working HTML page.


1 Answers

The rules are fast and loose on this, There is no right or wrong way only better and less-better. (well after the </html> is wrong)

Generally speaking, javascript in the head of the document might block rendering of the page until the file is loaded in some browsers *cough*IE*cough*. This is due to a limit of simultaneous connections. So some people put them before the closing html tag. You can use a library to asynchronously load the javascript to avoid this blocking.

If you're using a library, or checking for the DOM to be loaded before executing code there's really no issue of where it's placed. However if you're not doing that it's probably better to put it at the end.

like image 66
JKirchartz Avatar answered Sep 21 '22 05:09

JKirchartz