Where to put your <script> tags

Our practice so far in the course has been to put our <script> tags before the closing </body> tag in our HTML files. This is because when the browser encounters the <script> tag it blocks the parsing of the HTML and will not continue rendering the page until the JavaScript code has been downloaded and run. But the downside of including our JavaScript at the end of the HTML file is that the browser won’t start downloading the scripts at all until all of the page is parsed, which will affect the user experience if the files are very large.

In this week’s research spike we learned about the Critical Rendering Path, and how we can use the async or defer keywords in modern browsers to load our scripts in the <head> of our HTML files. These allow your scripts to be downloaded as soon as possible without blocking the HTML parsing.

Scripts with the async attribute are executed asynchronously in a casual order:
<script defer src="script.js"></script>

Scripts with the defer attribute are only executed after the entire document has been loaded: