Why we use script tag inside body instead of head?

 The placement of the <script> tag in an HTML document—whether inside the <head> or <body>—can impact the performance and behavior of the page, particularly with respect to how resources are loaded and how quickly the page becomes interactive. Here’s an explanation of why developers often place the <script> tag inside the <body> rather than the <head>, along with the implications of both choices.

1. Page Load Performance

Scripts in the <head>:

When the <script> tag is placed inside the <head>, the browser fetches and executes the JavaScript before rendering the content of the page. This can lead to delayed page rendering because the browser needs to download, parse, and execute the JavaScript before it proceeds to render the HTML. As a result, the page may take longer to display its content, especially if the script is large or if it's blocking other resources from loading.

Example:

<head> <script src="script.js"></script> </head> <body> <h1>Hello World!</h1> </body>

In this case:

  • The browser loads the page and hits the <script> tag in the <head>.
  • The script is fetched and executed before rendering the body content.
  • This means that the page is blocked from being fully rendered until the JavaScript is loaded and executed.

Scripts in the <body>:

When the <script> tag is placed at the end of the <body>, the browser loads the HTML content first and renders it to the screen. This allows the page to appear faster to the user because the browser doesn't block rendering while fetching and executing the script.

Once the content has been rendered, the browser will then load and execute the JavaScript. By this point, the DOM (Document Object Model) is ready, and the script can safely manipulate it without having to wait for the page to finish loading.

Example:

<body> <h1>Hello World!</h1> <script src="script.js"></script> </body>

In this case:

  • The HTML content is rendered first, making the page visible to the user.
  • The JavaScript is loaded and executed only after the page has been rendered.
  • This approach prevents blocking the page rendering process and improves perceived performance.

2. Blocking Behavior of JavaScript

JavaScript is traditionally a blocking operation. When a browser encounters a <script> tag, it stops everything else (like rendering HTML and CSS) until the script is fetched, parsed, and executed. If you place the script in the <head>, it blocks the browser from rendering the page until the script is processed.

Example:

<head> <script src="long-running-script.js"></script> </head> <body> <h1>Content</h1> </body>

In this example, even if the HTML body is large, the browser must wait for long-running-script.js to be processed before continuing with the page rendering.

3. DOM Availability

When scripts are placed in the <head>, they are executed before the DOM is fully available (i.e., before the body of the page is rendered). If your JavaScript manipulates DOM elements (such as adding event listeners or modifying content), the elements might not exist yet when the script runs. This can lead to errors or unexpected behavior.

Example:

<head> <script> document.querySelector("h1").style.color = "red"; // Error, h1 is not available yet </script> </head> <body> <h1>Heading</h1> </body>

If the script runs before the body has been parsed, the querySelector("h1") will fail because the <h1> element is not yet in the DOM.

Fix:

Placing the script at the end of the body ensures that the DOM is fully loaded by the time the script runs, making the elements available for manipulation.

<body> <h1>Heading</h1> <script> document.querySelector("h1").style.color = "red"; // This will work, as h1 is now available </script> </body>

Alternatively, you can use the defer or async attributes (more on this below) to control script loading without blocking rendering.

4. async and defer Attributes for <script> Tags

In some cases, you may want to place <script> tags in the <head> but still avoid blocking the rendering of the page. This can be achieved using the async or defer attributes, which modify how scripts are loaded and executed.

  • async: Scripts with the async attribute are fetched asynchronously and executed as soon as they are downloaded, without waiting for the rest of the page to load. However, this can cause issues if your script depends on other scripts or DOM elements, because execution order is not guaranteed.
<head> <script src="script.js" async></script> </head>
  • defer: Scripts with the defer attribute are also fetched asynchronously but are executed only after the HTML is fully parsed. This ensures that the DOM is ready before the script is executed, which makes defer more predictable and safer for DOM manipulation.
<head> <script src="script.js" defer></script> </head>

The defer attribute ensures the script doesn't block HTML rendering, and it guarantees execution order if there are multiple deferred scripts.

5. Best Practices

  • Place scripts at the end of the <body>: This is the most common and recommended practice. It ensures that the page renders as quickly as possible and that JavaScript doesn't block the page content from appearing. It also ensures that the DOM is available when the script runs.

  • Use async or defer if placing scripts in the <head>: If you need to place your <script> tags in the <head>, use the defer attribute to ensure that scripts are executed only after the page content has loaded. If you don’t need to guarantee execution order, use async.

Conclusion

  • Placing <script> in the <body> (usually at the end) improves page load performance by allowing HTML to be rendered first, before executing JavaScript.
  • Placing <script> in the <head> can cause delays in rendering because the browser must load and execute the JavaScript before continuing with the HTML. However, you can use async or defer to manage script execution in the <head> without blocking rendering.
  • Always ensure your script does not manipulate DOM elements before they are available by placing scripts at the end of the <body> or using proper loading attributes.

By placing your scripts wisely, you can create more efficient, responsive web pages.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

Building strong foundational knowledge in frontend development topics