Skip to main content

What does the defer attribute do on <script>?

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.


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

AttributeHow it worksExecution order
no attributeStops the HTML load, runs immediatelyAs encountered
asyncLoads asynchronously and runs right after loadingArbitrary order
deferLoads asynchronously, runs after the DOM is builtIn inclusion order

Summary:

PropertyValue
PurposeDelays script execution until the HTML loads
Works only withExternal files (<script src="...">)
PriorityRuns after the DOM is built
Execution orderPreserved as in the code
AdvantageSpeeds 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.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.