Async Components — Vue

defineAsyncComponent(() => import("./OrderHistory.vue")) makes an async component: its code is downloaded separately on its first render, then kept. The…

The order history book at Mrs. Sri's stall is thick and rarely opened. Mrs. Sri doesn't bring it to the cashier's desk every morning. It stays in the storeroom, and someone fetches it only when a customer asks about an old order. The first time, fetching it takes a moment. After that, the book is already on the desk.

A big component that's rarely used can be treated the same way. An async component is a component whose code is only downloaded the first time it's needed, instead of being part of the page's first download. In the picture, the history book is the component, the cashier's desk is the page already open in the browser, and fetching the book from the storeroom is downloading that component's code. Vue makes an async component with defineAsyncComponent().

defineAsyncComponent: downloaded on its first render

The button below opens and closes the order history. OrderHistory is an async component:

<script setup>
import { ref, defineAsyncComponent } from "vue"

const OrderHistory = defineAsyncComponent(() => import("./OrderHistory.vue"))
const open = ref(false)
</script>

<template>
  <button @click="open = !open">Order history</button>
  <OrderHistory v-if="open" />
</template>

This table shows what the browser downloads and what shows. The main bundle is the combined JavaScript file that is downloaded when the page opens:

Event What is downloaded What shows
The page opens the main bundle only the Order history button
First click a separate file, such as OrderHistory-a1b2c3.js nothing yet, until the download finishes
The download finishes nothing the history list
Close, then open again nothing, it's already kept the history list, right away

The exercise editor and the Playground have no .vue file to import. So a loader only needs to be a function that returns a Promise holding a component. defineAsyncComponent is called through the Vue object that the editor provides:

const open = ref(false)
const OrderHistory = Vue.defineAsyncComponent(() =>
  new Promise((resolve) => {
    setTimeout(() => resolve({ template: "<ul><li>Fried Rice $15</li></ul>" }), 1000)
  })
)

---template---
<button @click="open = !open">Order history</button>
<component v-if="open" :is="OrderHistory" />

In this example, resolve fills the Promise with the component after 1 second, like a download that takes time.

In the second exercise, you use the form above without the pause: const Lazy = Vue.defineAsyncComponent(() => Promise.resolve({ template: ... })). Then <component v-if="loaded" :is="Lazy" /> only shows after the #load button sets loaded to true. The checker also looks for defineAsyncComponent( in your code.

Loading, error, delay, timeout

While downloading, an async component shows nothing. So that the customer knows the history is loading, use the object form:

const OrderHistory = defineAsyncComponent({
  loader: () => import("./OrderHistory.vue"),
  loadingComponent: HistoryLoading,   // shows while downloading
  delay: 200,                        // default: wait 200 ms before loadingComponent shows
  errorComponent: LoadFailed,       // shows if the download fails
  timeout: 3000,                     // counts as failed after 3 seconds
})

Say HistoryLoading shows "Loading history..." and LoadFailed shows "History failed to load". This table shows what appears for each download speed:

Download What shows
finishes in 150 ms empty for a moment, then the history list. "Loading history..." never gets to show
finishes in 1.5 seconds empty for 200 ms, then "Loading history...", then the history list
fails "History failed to load" from errorComponent; without errorComponent, the space stays empty, or "Loading history..." never disappears. The error is always written to the console
1.5 seconds with timeout: 1000 errorComponent after 1 second, then the history list when the download finally finishes

In the table's first row, "Loading history..." doesn't get to show. The default delay is 200 ms, and a 150 ms download is done before then. The delay is on purpose: on a fast connection, a loading text that appears for an instant and disappears feels like a flicker. Write delay: 0 if the loading must show right away.

When the signal is weak, the option onError(error, retry, fail, attempts) can repeat a failed download. retry() tries again, fail() gives up, and attempts is the number of tries so far. For example, if (attempts <= 3) retry(); else fail() repeats the download while attempts is 3 or less, and gives up with fail() once it's more than 3. We tried it on Vue 3.5.45 with a download that failed twice: the third try worked, and the history list showed.

Suspense: one fallback for what's async

A component whose setup waits for something, such as <script setup> with await outside any function, is said to have an async setup. The Fetching Data lesson called it an async component. It is different from an async component made with defineAsyncComponent above: what is waited for is its setup, not the download of its code. A component with an async setup must be wrapped in <Suspense>, a built-in Vue component that waits:

<!-- OrderHistory.vue -->
<script setup>
const res = await fetch("/api/history")
const list = await res.json()
</script>

<!-- App.vue -->
<template>
  <Suspense>
    <OrderHistory />
    <template #fallback>
      <p>Loading history...</p>
    </template>
  </Suspense>
</template>

⚠️ Async components that never appear, or aren't worth it

TL;DR: defineAsyncComponent(() => import("./OrderHistory.vue")) makes an async component: its code is downloaded separately on its first render, then kept. The component is split into its own file (code splitting), so the main bundle (the file downloaded when the page opens) is smaller. Its object form adds loadingComponent (shown after delay, 200 ms by default), errorComponent (shown if it fails) and timeout (the time limit before it counts as failed). <Suspense> shows its #fallback slot until the components with an async setup (a setup that uses await) and the async components inside it are ready. Without Suspense, a component with an async setup never shows. Use async components for parts that are big and rarely used.

⚡ Downloaded on its first render

Write:

<script setup>
import { ref, defineAsyncComponent } from "vue"

const OrderHistory = defineAsyncComponent(() => import("./OrderHistory.vue"))
const open = ref(false)
</script>

<template>
  <button @click="open = !open">Order history</button>
  <OrderHistory v-if="open" />
</template>

Meaning: OrderHistory is an async component: its code is only downloaded the first time it's needed. () => import(...) is the loader (the function that downloads the component), and Vue only calls it the first time OrderHistory is rendered, here when open becomes true. The component is split into its own file. This is called code splitting. Its main benefit: the main bundle (the file downloaded when the page opens) is smaller, so the first page shows sooner.

⚡ Loading text and delay

Write:

const OrderHistory = defineAsyncComponent({
  loader: () => import("./OrderHistory.vue"),
  loadingComponent: HistoryLoading,
  delay: 200,
  errorComponent: LoadFailed,
  timeout: 3000,
})
Guess first: HistoryLoading shows "Loading history...", and delay: 200 means wait 200 ms before that component shows. The download finishes in 150 ms. Does that text get to show?

It doesn't. A 150 ms download is done before 200 ms. The delay is on purpose, so loading text doesn't flash for an instant. 200 ms is also the default delay.

Meaning: This is the object form of defineAsyncComponent. loadingComponent shows while downloading, errorComponent if it fails, and timeout counts the download as failed after 3 seconds.

⚡ Suspense for an async setup

Write:

<Suspense>
  <OrderHistory />
  <template #fallback>
    <p>Loading history...</p>
  </template>
</Suspense>

Meaning: <Suspense> is a built-in Vue component that waits until the components inside it are ready. Here the setup of OrderHistory waits for something: its <script setup> has await directly in it, outside any function. A component whose setup waits must be wrapped in <Suspense>. The #fallback slot shows until everything is done. Without <Suspense>, the component never shows.

What you will learn