Does script tag have to be in the head?

LAST READ: APR 14 2024 | Q. BY: JAMS SIMON

B

Bright Madhu

Script Tag Have a Head

The answer is No, the <script> tag does not have to be placed in the <head> section of the HTML document. Actually, placing scripts that are essential for page functionality in the <head> section is a good practice to ensure they are loaded and executed early in the page load process.


How to the <script> tag used in HTML <head>?

  • Using scripts that need to be loaded and executed before the content of the page is displayed. 
  • Using scripts that are required by other elements in the <head> section, such as scripts for polyfills or libraries that need to be available early in the page loading process.


Code Example of <script> Tag

<head>

  <script src="script1.js" defer></script>

</head>


Placing Scripts Before </body> Tag

  • Using scripts that are not critical for the initial page load but placing non-essential scripts at the end of the document allows the main content to load first, improving the perceived performance of the website.
  • When using scripts that rely on elements defined in the <body> section. Placing the scripts at the end ensures that all elements in the <body> are already parsed and available to the scripts.


Code Example of <script> Tag Before </body>

<body>

  <script src="script2.js" defer></script>

</body>

1 votes

Your Answer

Email Us: advertise@gdatamart.com

Donate Us: Support to GDATAMART

LifeStyle & Fun

© 2024 GDATAMART.COM (All Rights Reserved)