MediumConcept

What is the difference between async and defer on script tags?

Technology:
HTML,
JavaScript
Experience:
Mid-level,
Senior

Quick answer

Both download the script without blocking HTML parsing. defer waits until parsing finishes and runs scripts in document order; async runs a script as soon as it is downloaded, which can be before or after parsing and in any order.

Detailed explanation

A classic <script src> in the head blocks parsing until the file is downloaded and executed. defer is the right default for module-style application code that depends on the DOM and on other scripts. async is for independent tags such as analytics, where order does not matter.

type="module" scripts are deferred by default. async and defer have no effect on inline scripts. Put critical, tiny inline scripts only when you must paint something before the main bundle arrives.

  • JavaScriptMedium

    What is event delegation in JavaScript?

    Event delegation means attaching one listener to a parent element and using event bubbling to handle events from its children, instead of adding a listener to each child.

    Junior 路 Mid-level 路 Browser & DOM
  • JavaScriptMedium

    What is the event loop in JavaScript and how does it work?

    The event loop is the mechanism that lets single-threaded JavaScript handle asynchronous work: it runs the call stack to empty, then runs all queued microtasks (promises), then takes the next task (timers, events) from the queue.

    Mid-level 路 Senior 路 Asynchronous Programming
  • HTMLMedium

    How does the browser render a web page?

    The browser parses HTML into a DOM and CSS into a CSSOM, combines them into a render tree, computes layout (reflow), paints pixels and composites layers onto the screen.

    Mid-level 路 Senior 路 Browser & DOM
  • JavaScriptHard

    How do you find and fix memory leaks in JavaScript?

    Take heap snapshots in Chrome DevTools before and after the suspect action, compare what grew, and fix the retaining reference, which is usually a forgotten listener, timer, global variable or unbounded cache.

    Senior 路 Memory Management