Where should we put <script> tags in HTML markup ?
Here's what happens when a browser loads a website with a <script> tag on it:
- Fetch the HTML page (e.g. index.html)
- Begin parsing the HTML
- The parser encounters a <script> tag referencing an external script file.
- The browser requests the script file. Meanwhile, the parser blocks and stops parsing the other HTML on your page.
- After some time the script is downloaded and subsequently executed.
- The parser continues parsing the rest of the HTML document.
The modern approach
Today, browsers support the async and defer attributes on scripts. These attributes tell the browser it's safe to continue parsing while the scripts are being downloaded.
Non-blocking script tags can be placed just about anywhere:
- async script will be executed asynchronously as soon as it is available
- defer script is executed when the document has finished parsing
- async defer script falls back to the defer behavior if async is not supported
Such scripts will be executed asynchronously/after document ready, which means cannot do this: