Script Loading Strategies
What you'll learn: How to position <script> tags and use defer and async attributes to prevent your JavaScript from blocking page rendering.
The Problem with Default Script Loading
When the browser encounters a <script> tag while parsing HTML, it stops everything. It downloads the script, executes it immediately, then continues parsing. This is like a delivery truck blocking the entire road until it's fully unloaded—nothing else can move forward.
Where to Put Scripts
Traditionally, scripts were placed in the <head>, but this delays page rendering. The modern best practice is placing them just before the closing </body> tag, so the entire page structure loads first.
The defer Attribute
<script src="app.js" defer></script>
Scripts with defer download in the background without blocking HTML parsing. They execute after the entire document is parsed, in the order they appear. Think of it as telling the delivery truck: "Park over there, I'll deal with you when I'm done setting up."
Best for: Scripts that need the full DOM ready and must run in a specific order.
The async Attribute
<script src="analytics.js" async></script>
Scripts with async also download in the background, but they execute immediately when ready, potentially out of order. This is like telling independent delivery trucks: "Just drop off whenever you arrive."
Best for: Independent scripts that don't rely on the DOM or other scripts (analytics, ads).
Quick Reference
- No attribute: Blocks parsing, executes immediately
defer: Non-blocking download, executes after parsing, in orderasync: Non-blocking download, executes ASAP, order not guaranteed
Key Takeaway: Use defer for most scripts, async for independent third-party scripts, and place scripts at the end of <body> as a fallback for maximum performance and user experience.