0
0
Vueframework~5 mins

Lazy loading components in Vue

Choose your learning style9 modes available
Introduction

Lazy loading components helps your app load faster by only loading parts when needed. It saves time and data by not loading everything at once.

When you have a big app with many components and want faster startup.
When some components are only used after user actions, like clicking a button.
When you want to reduce initial data usage for users on slow connections.
When you want to improve user experience by showing important parts first.
Syntax
Vue
import { defineAsyncComponent } from 'vue'
const MyComponent = defineAsyncComponent(() => import('./MyComponent.vue'))
Use defineAsyncComponent from Vue to create a lazy loaded component.
The component is loaded only when it is actually needed in the app.
Examples
This example shows how to create a lazy loaded component called LazyComp.
Vue
import { defineAsyncComponent } from 'vue'

const LazyComp = defineAsyncComponent(() => import('./LazyComp.vue'))
Using the lazy loaded component inside a template with defineAsyncComponent.
Vue
<template>
  <LazyComp />
</template>

<script setup>
import { defineAsyncComponent } from 'vue'
const LazyComp = defineAsyncComponent(() => import('./LazyComp.vue'))
</script>
Lazy loading with a loading spinner shown after 200ms delay.
Vue
const LazyComp = defineAsyncComponent({
  loader: () => import('./LazyComp.vue'),
  loadingComponent: LoadingSpinner,
  delay: 200
})
Sample Program

This Vue component shows a button to toggle a lazy loaded component. The component loads only when you click the button. While loading, it shows a fallback message.

Vue
<template>
  <button @click="show = !show">Toggle Lazy Component</button>
  <Suspense>
    <template #default>
      <LazyComponent v-if="show" />
    </template>
    <template #fallback>
      <p>Loading component...</p>
    </template>
  </Suspense>
</template>

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

const show = ref(false)
const LazyComponent = defineAsyncComponent(() => import('./LazyComponent.vue'))
</script>
OutputSuccess
Important Notes

Lazy loading helps reduce initial load time but may cause a small delay when the component first appears.

Use <Suspense> in Vue to show fallback content while loading.

Lazy loading is great for big apps or rarely used parts.

Summary

Lazy loading loads components only when needed to speed up app start.

Use defineAsyncComponent to create lazy loaded components in Vue.

Combine with <Suspense> to show loading states nicely.