# Top-level await

> The top-level `await` in JS allows using the `await` keyword at the top level of modules outside of async functions.

## How do I use await at the top level in JavaScript?

The ability to use the `await` keyword directly at the top level of an ES module. The module waits for the promise to settle before executing modules that import it. Useful for loading configuration, data or dynamic dependencies.

- Topic: Syntax
- Type: syntax
- Browser support: Chrome 89+, Chrome Android 89+, Edge 89+, Firefox 89+, Firefox Android 89+, Safari 27+, Safari iOS 27+

## Example

Wrong:

```html
<script>
  const res = await fetch('/config.json');
  const config = await res.json();
</script>
```

Right:

```html
<script type="module">
  const res = await fetch('/config.json');
  const config = await res.json();
</script>
```

Top-level `await` works only in modules, so the classic script throws a syntax error.

## Common mistakes

- Using top-level `await` in a classic script and getting a syntax error.

## Key points

- The file is an ES module, for example loaded with `<script type='module'>`.
- Top-level `await` is not used in modules that many others import, because every importing module waits for it.
- Failures are handled with `try...catch`, so one rejected promise does not break the whole module graph.

## Interview questions

### Does top-level await block other modules?

It delays only modules that import this one, until its promise settles. Modules that do not depend on it keep loading and can run.

### Is top-level await the same as an async IIFE?

No. With top-level `await`, importing modules wait for the result; with an async IIFE, they run before the async work finishes.

### What happens if a top-level await promise rejects?

The module fails to evaluate, and every module that imports it fails with the same error.

## Related cards

- [async / await](https://wonderium.dev/js/async-await.md)
- [import / export](https://wonderium.dev/js/import-export.md)
- [`<script type="importmap">`](https://wonderium.dev/html/import-map.md)
- [Promise](https://wonderium.dev/js/promise.md)

---

- Level: [JavaScript](https://wonderium.dev/js.md)
- HTML version: https://wonderium.dev/js/top-level-await
- Last updated: 2026-11-25
