Intermediate LevelHTML & Semantic Web
What is the difference between async and defer attributes on script tags?
❓ Interview Prompt: Compare synchronous script execution vs async (asynchronous downloading and immediate execution) vs defer (deferred execution after DOM parsing).
Controlling script loading behavior is critical for page load performance:
1. Synchronous '<script src="...">':
•
Pauses HTML parsing immediately, downloads script, executes it, then resumes HTML parsing. Blocks DOM construction!
2. '<script async src="...">':
•
Downloads script asynchronously in background while HTML parsing continues.
•
Executes immediately when download completes, pausing HTML parsing. Does NOT guarantee script execution order!
3. '<script defer src="...">' (Recommended for app bundles):
•
Downloads script asynchronously in background.
•
Executes ONLY after HTML document parsing is completely finished, right before 'DOMContentLoaded'. Guarantees script execution order!
Code Implementation Example
html
<!-- Non-blocking async analytics script -->
<script async src="https://analytics.example.com/tracker.js"></script>
<!-- Non-blocking deferred main application bundle -->
<script defer src="/js/app.js"></script>💡Script loading comparison: synchronous vs async vs defer.
🎯 Interview Key Takeaway
Use defer for application scripts to preserve DOM parsing and execution order; use async for independent third-party analytics.
#script tag#async#defer#Performance#Intermediate
Back to all HTML & Semantic Web Questions→