Where you put a script, and how you load it, affects how fast your page appears.
The problem
When a browser reads HTML and meets a normal script, it stops, downloads and runs the script, and only then continues. A slow script in the head can leave a visitor looking at a blank page.
Option 1: at the end of the body
Place scripts just before </body>. By then the page content already exists.
<body>
...page content...
<script src="app.js"></script>
</body>
Option 2: defer (recommended)
defer lets the script download while the page loads and runs it after the HTML is read. You can keep it in the head.
<head>
<script src="app.js" defer></script>
</head>
Deferred scripts run in the order they appear.
Option 3: async
async downloads the script and runs it as soon as it is ready, in any order. It is good for independent scripts such as analytics, and bad for scripts that depend on each other.
| Attribute | Runs when | Order kept |
|---|---|---|
| none | Immediately, blocking the page | Yes |
defer | After the HTML is parsed | Yes |
async | As soon as it downloads | No |
Running a script before its elements exist
defer, or place the script after the element.