Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
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
-
deferonly works with external scripts (those withsrcattribute) - 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.
Advertisements
