How exactly does work?

The defer attribute tells the browser to download the script while parsing HTML but delay execution until the DOM is fully built. It only works with external scripts and maintains execution order.

How defer Works

HTML Parsing Script Download Script Execution 1. HTML parsing continues while script downloads 2. Script waits until DOM is complete 3. Scripts execute in document order

Example: defer vs Normal Script

<!DOCTYPE html>
<html>
<head>
    <script src="script1.js" defer></script>
    <script src="script2.js" defer></script>
</head>
<body>
    <h1 id="heading">Page Content</h1>
    <p>Both deferred scripts will run after DOM is ready.</p>
</body>
</html>

Script Content Example

Contents of script1.js:

console.log("Script 1: DOM ready?", document.readyState);
document.getElementById("heading").style.color = "blue";

Contents of script2.js:

console.log("Script 2: DOM ready?", document.readyState);
document.getElementById("heading").textContent = "Modified by Script 2";

Execution Order

Script 1: DOM ready? complete
Script 2: DOM ready? complete

Comparison: defer vs async vs normal

Attribute Download Timing Execution Timing Execution Order
Normal Blocks HTML parsing Immediately after download Document order
defer Parallel with HTML parsing After DOM complete Document order
async Parallel with HTML parsing Immediately after download Download completion order

Key Points

  • defer only works with external scripts (those with src attribute)
  • Multiple deferred scripts execute in the order they appear in the document
  • DOM elements are guaranteed to be available when deferred scripts run
  • Perfect for scripts that need to manipulate DOM elements

Conclusion

Use defer for external scripts that need DOM access. It ensures non-blocking downloads while maintaining execution order after the DOM is complete.

Updated on: 2026-03-15T23:18:59+05:30

319 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements