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
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.
The <script> Tag In HTML, JavaScript code is inserted between <script> and </script> tags.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With