It is generally discouraged to load your JavaScript by a <script src> tag in the <head>:
<head>
<script src="app.js"></script>
</head>
The reason is that a <script src> tag will pause the DOM parser until the script has loaded and executed. This will delay the browser's
first contentful paint
Show archive.org snapshot
.
A much better default is to load your scripts with a <script src defer> tag:
<head>
<script src="app.js" defer></script>
</head>
A deferred script has many useful properties:
- It does not block the browser from rendering content.
- Deferred scripts will run after the HTML was parsed. That means you can query the entire DOM tree with
querySelector()and friends.document.readyStateis'interactive'. - Deferred scripts will run before the
DOMContentLoadedevent. That means if your code waits to initialize untilDOMContentLoaded(many libraries do), it will still work. - If you have multiple deferred scripts, they will run in the order they appear in the HTML, regardless of how long individual scripts take to load.
- You can put your
<script>in the<head>, meaning browsers can start loading the script file very early. - The
<script>tag is grouped together with your other external resources in the<head>.
Deferring inline scripts
You cannot defer inline <script> tags. However, you can use <script type="module">, which is deferred by default:
<script type="module">
console.log("I'm running deferred")
</script>
Posted by Henning Koch to makandra dev (2021-08-31 11:14)