When we have to use <script>
tag inside <head>
section and when we have to use the <script>
tag inside <body>
section? What is the difference between these two occurrences?
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.
When you place a script in the head section, you will ensure that the script is loaded before anyone uses it. Scripts in the body section: Scripts to be executed when the page loads go in the body section. When you place a script in the body section it generates the content of the page.
The script tag should always be used before the body close or at the bottom in HTML file.
The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load. Generally, JavaScript code can go inside of the document <head> section in order to keep them contained and out of the main content of your HTML document.
Scripts in <head>
Scripts to be executed when they are called, or when an event is triggered, are placed in functions.
Put your functions in the head section, this way they are all in one place, and they do not interfere with page content.
Scripts in <body>
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. This can improve page load, because script compilation can slow down the display.
In short and simple language:
Place library script such as the jQuery library in the head section.
Place normal script in the head unless it becomes a performance/page load issue.
Place script that impacts the render of the page at the end of the body
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