Where to put JavaScript? (Performance matters!)
The problem: When browser sees <script>, it stops loading the page until the script downloads and runs. User sees blank screen.
The 4 Ways to Place Scripts:
1<!-- 1. BAD: In head (blocks page loading completely) -->
2<head>
3 <script src="script.js"></script>
4</head>
5
6<!-- 2. GOOD: At end of body (page loads first) -->
7<body>
8 <h1>Content loads first</h1>
9 <p>User sees this immediately</p>
10 <script src="script.js"></script>
11</body>
12
13<!-- 3. BEST: defer (waits for HTML to load fully) -->
14<script src="main.js" defer></script>
15
16<!-- 4. GOOD: async (loads independently, good for analytics) -->
17<script src="analytics.js" async></script>defer vs async Explained:
Attribute | When it downloads | When it runs | Best for |
|---|---|---|---|
No attribute | Immediately | Immediately (blocks HTML) | Never use in head |
| In background while HTML loads | After HTML is fully loaded | Scripts that need the page (DOM manipulation) |
| In background while HTML loads | As soon as downloaded (may interrupt HTML) | Independent scripts (analytics, ads) |
Visual explanation:
Without defer/async:
[HTML loading] [STOP] [Script downloads & runs] [Continue HTML]User sees blank screen while script loads
With defer:
[HTML loading + Script downloading in background] [HTML done] [Script runs]User sees content quickly, script runs after
With async:
[HTML loading] [Script downloads & runs anytime - may interrupt]Script runs when ready, may pause HTML loading
Which one to use?
Use
deferfor your main JavaScript (it needs the page to be ready)Use
asyncfor analytics, ads, or independent scriptsNever put scripts in
<head>without defer/async
