JavaScript JavaScript Basics (Retired) Introducing JavaScript Review Adding Scripts and Simple JavaScript Commands

What is the best practice of writing javascript either inside end of the body tag or inside end of the head tag ?

where to add javascript for the best pactice

1 Answer

andren
andren
28,457 Points

The best practice these days is to place it at the end of the body tag. Modern browsers pause page rendering while they parse and execute JavaScript.

This means that if you place JavaScript in the head element then your page won't display any content before the browser is done with the JavaScript. Placing it at the end of the body avoids this problem as the page content has already loaded by then.

As an added bonus you'll be guaranteed that all the HTML elements are loaded when your script runs, which they need to be if you want to manipulate them in your code.