difference js code in head and in body

‮www‬.lautturi.com
difference js code in head and in body

The main difference between placing JavaScript code in the head of an HTML document versus the body is when the code is executed. If you place the script element in the head of the document, the JavaScript code will be executed as soon as it is loaded, which is typically before the content of the page is loaded. This can be useful if you want to perform some setup tasks or configuration before the page is rendered.

However, if you place the script element at the bottom of the body element, the code will be executed after the content of the page has been loaded. This can be beneficial for improving the performance of your web page, as the user will not have to wait for the JavaScript code to be executed before the content of the page is displayed.

Additionally, placing the script element at the bottom of the body element can also help to ensure that the elements that the JavaScript code interacts with are available in the DOM (Document Object Model) and can be accessed by the code. If you place the script element in the head of the document, there is a risk that the code will execute before the relevant elements have been rendered, which could lead to errors or unexpected behavior.

In general, it is a good practice to place the script element at the bottom of the body element, unless you have a specific reason to do otherwise.

Created Time:2017-10-16 14:38:55  Author:lautturi