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:
querySelector()
and friends. document.readyState
is 'interactive'
.DOMContentLoaded
event. That means if your code waits to initialize until DOMContentLoaded
(many libraries do), it will still work.<script>
in the <head>
, meaning browsers can start loading the script file very early.<script>
tag is grouped together with your other external resources in the <head>
.