defer, & asyncJavaScript scripts can be integrated into HTML documents in three primary locations: inline attributes, internal <script> blocks, or external .js files. Proper placement and loading attributes directly govern page load performance and Critical Rendering Path optimization.
flowchart TD
subgraph Standard ["Default <script>"]
HTML1["HTML Parsing"] --> Stop1["Pause HTML"] --> Fetch1["Fetch & Execute Script"] --> HTML2["Resume HTML"]
end
subgraph Async ["<script async>"]
HTML3["HTML Parsing (Parallel Fetch)"] --> Interrupt["Pause Parsing & Execute JS Immediately"] --> ResumeHTML["Resume HTML"]
end
subgraph Defer ["<script defer>"]
HTML4["HTML Parsing (Parallel Fetch)"] --> ParseDone["DOM Parsing Finished"] --> ExecDefer["Execute Deferred JS"]
end
| Attribute | HTML Parsing Interrupted? | Execution Order Guaranteed? | Ideal Use Case |
|---|---|---|---|
Default <script> |
Yes (Blocks DOM parsing) | Yes (In document order) | Critical scripts required before rendering body. |
async |
Yes (Executes immediately when downloaded) | No (Executes as soon as ready) | Independent scripts (Analytics, Ads, Tracking). |
defer |
No (Waits until DOM parsing completes) | Yes (Executes in document order) | Application logic needing full DOM structure. |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Script Placement Demo</title>
<!-- External Script with defer: Non-blocking, executes after DOM is parsed -->
<script src="app.js" defer></script>
<!-- External Script with async: Independent analytics script -->
<script src="analytics.js" async></script>
</head>
<body>
<h1>JavaScript Loading Strategies</h1>
<p id="content">Parsing HTML content...</p>
<!-- Internal Script placed at end of <body> as fallback -->
<script>
document.addEventListener("DOMContentLoaded", () => {
console.log("DOM fully loaded and parsed!");
const contentEl = document.getElementById("content");
if (contentEl) {
contentEl.textContent = "DOM Content Parsed Successfully.";
}
});
</script>
</body>
</html>
defer: Keep HTML clean, leverage browser caching, and prevent render-blocking by using defer on external scripts in <head>.defer/async on Inline Scripts: Modern browsers ignore defer and async on inline <script>...</script> blocks without a src attribute.async: Never use async if Script B relies on functions or objects defined in Script A.Explain why placing a heavy synchronous <script src="heavy.js"></script> without defer inside the <head> tag causes a "white screen of death" phenomenon on slow mobile networks.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.