Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use the <script> tag in the head and body section of a html page? [duplicate]

Tags:

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?

like image 694
JCA Joe Avatar asked Jul 16 '16 05:07

JCA Joe


People also ask

Should script tags be 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 is the difference when the script tag appears in the HTML body or head sections?

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.

Where is the script tag used in the head tag in the body tag in the head and body tags nowhere?

The script tag should always be used before the body close or at the bottom in HTML file.

Does the script tag go in the head?

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.


Video Answer


1 Answers

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:

  1. Place library script such as the jQuery library in the head section.

  2. Place normal script in the head unless it becomes a performance/page load issue.

  3. Place script that impacts the render of the page at the end of the body

like image 170
Shubham Khatri Avatar answered Oct 31 '22 22:10

Shubham Khatri