HTML, CSS & the Browser

Async Attribute

Definition

Written as script src="tracker.js" async, it tells the browser to fetch the file alongside parsing and execute it as soon as the download finishes — possibly before the document has been fully parsed, possibly after, and possibly in a different order from the tags on the page. Two async scripts requested together run in whichever order arrives first, which on a variable connection is not predictable from one load to the next. Execution itself still pauses the parser for as long as the script takes, so a large async file can interrupt rendering halfway down the page. Like defer, the attribute works only on external files and does nothing on an inline one.

Why It Matters

Async suits a narrow set of files and is wrong for most. It fits a script that depends on nothing and that nothing depends on: an analytics beacon, an error reporter, an advertising tag. Put a library on async and the file using it can run first, producing an is-not-defined error that appears on some loads and not others — the worst kind to chase, because it is a race and refreshing usually hides it. If the script touches the page at all, defer is almost certainly what was wanted.

How It Works

On meeting the tag the parser starts the download and keeps going. When the file lands, parsing stops, the script runs to completion, and parsing resumes, so an async file arriving halfway through can delay the rest of the page by however long it takes to execute. It may run before or after DOMContentLoaded, which is why an async script cannot assume any element exists and has to check for itself. Writing both attributes together means async in any browser that supports it, and there is no reason to write both today. Modules behave like defer by default and take async as an explicit opt-in.

Real-World Example

A long-form case study at rollout-story.99helpers.site loads a charting library with async, and the small page script that draws with it async as well. It works on the author's machine and fails for roughly one visitor in five with a not-defined error, because on a slower connection the small file arrives first. Switching both to defer fixes it for good: the same two files, the same total size, a guaranteed order.

Common Mistakes

  • Using async for a library and the code that calls it — the order is not guaranteed, so the bug shows up only on certain connections
  • Reaching for async because it sounds faster — it is no faster to first paint than defer, and it can stall the parser mid-page
  • Assuming an async script can query the page — it may run before the element it needs has been parsed at all

Related Terms

Put a file online in seconds

Drop in a document, an image, a page or a whole static website and share the link — free, with no build step and no server to set up.

Host a file free →