Suggest an editImprove this articleRefine the answer for “What does the defer attribute do on <script>?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**The `defer` attribute** on the `<script>` tag delays the execution of JavaScript code until the browser has fully loaded and parsed the HTML document. It lets you place scripts in `<head>` without risking "freezing" the page load. **Key point:** `defer` loads the script asynchronously but runs it only after the DOM is fully built, and in the order the scripts were included.Shown above the full answer for quick recall.Answer (EN)ImageThe `defer` attribute on the `<script>` tag delays the execution of JavaScript code **until the browser has fully loaded and parsed the HTML document**. It lets you place scripts in `<head>` without risking "freezing" the page load. --- ### 1. The problem without defer By default, if you include a script like this: ```html <script src="main.js"></script> ``` the browser **stops building the page**, loads and runs `main.js`, and only then continues reading the HTML. This slows down the loading and rendering of content (especially if the script is large). --- ### 2. What defer does If you add `defer`: ```html <script src="main.js" defer></script> ``` The browser: 1. Starts **loading the script asynchronously** (in parallel with the HTML); 2. **Does not stop** page rendering; 3. Runs the script **only after the HTML is fully loaded**, that is, once the DOM is ready. Put simply: > `defer` = "download it ahead of time, but run it later, once everything is built". --- ### 3. When to use it `defer` is ideal for **scripts that work with page elements (the DOM)**: ```html <head> <script src="menu.js" defer></script> <script src="slider.js" defer></script> </head> ``` Both scripts run **in the order they were included**, after the HTML loads. --- ### 4. Difference from async | Attribute | How it works | Execution order | |---|---|---| | **no attribute** | Stops the HTML load, runs immediately | As encountered | | `async` | Loads asynchronously and runs right after loading | Arbitrary order | | `defer` | Loads asynchronously, runs after the DOM is built | In inclusion order | --- ### Summary: | Property | Value | |---|---| | Purpose | Delays script execution until the HTML loads | | Works only with | External files (`<script src="...">`) | | Priority | Runs after the DOM is built | | Execution order | Preserved as in the code | | Advantage | Speeds up page loading and does not block rendering | --- **In simple terms:** `defer` tells the browser: > "Download this script now, but run it once the page has fully loaded". This makes the site faster and prevents errors when JavaScript tries to access elements that are not yet in the DOM.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.