🔄 Script Loading: async vs defer vs Both
Category: js / general-concepts
Difficulty: hard
Understanding when to use async, defer, or both attributes on <script> tags to optimize page loading performance and avoid render-blocking issues. 💡 What are Script Loading Attributes? Script loading attributes control how and when JavaScript files are downloaded and executed, preventing render-blocking and improving page performance. Why it matters: Default <script> tags block HTML parsing and rendering, causing slow page loads and poor user experience. 🧠 Core Concepts Default Behavior (No Attributes) [code example] What happens: HTML parsing stops Script downloads Script executes immediately HTML parsing resumes Impact: Slows First Contentful Paint, blocks rendering. defer Attribute [code example] What happens: Download starts in parallel with HTML parsing HTML parsing continues uninterrupted Script executes after DOM is complete Multiple deferred scripts run in order Best for: Application scripts that need DOM access. async Attribute [code example] What happens: Download starts in parallel with HTML parsing HTML parsing continues Script executes as soon as download completes May interrupt HTML parsing if downloaded early Best for: Independent scripts (analytics, ads, widgets). async defer (Both) [code example] What happens: async takes precedence, defer is ignored. Same as async only. ✅ When to Use Each Approach Use defer for: Application scripts that manipulate DOM Scripts that depend on each other (maintains execution order) Scripts that need DOM to be ready Most JavaScript in modern web apps [code example]...