Home > Blockchain >  HTML JavaScript Script Tag
HTML JavaScript Script Tag

Time:05-08

Why are javascript <script> tags placed in the <body> rather than the other script tags which are usually placed in the <head>?

CodePudding user response:

  1. JavaScript is blocking; it is often desirable prioritise rendering HTML over loading of JS.
  2. JavaScript often needs to access elements in the DOM during its initial execution (e.g. to add event listeners). Those elements need to exist before the JS can access them. Placing the <script> element after the elements it needs to access is one way to achieve this.

The introduction of the defer attribute allows both these benefits to be gained while leaving the <script> element in the <head> which also allows the HTTP request for the JS to run in parallel. Not everybody has caught up with this development.

CodePudding user response:

It can be placed either in <body> or <head>, there is not really a difference in performance or anything. It's just a conceptual thing to keep any "importing" stuff in the head section.

  • Related