JAVASCRIPT

Lazy Load Components with Vue 3 defineAsyncComponent

Optimize Vue 3 application performance by lazy loading components only when needed using `defineAsyncComponent` and `<Suspense>`, reducing initial bundle size and improving user experience for large apps.

// src/views/AboutView.vue (or any large component)
// This component will be loaded on demand

// src/App.vue (or a parent component)
<template>
  <div>
    <h1>Welcome to My App</h1>
    <button @click="showAbout = !showAbout">Toggle About Section</button>

    <Suspense v-if="showAbout">
      <template #default>
        <AboutSection />
      </template>
      <template #fallback>
        <div>Loading About section...</div>
      </template>
    </Suspense>
  </div>
</template>

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

const showAbout = ref(false);

// Define the AboutSection component as an async component
const AboutSection = defineAsyncComponent(() =>
  import('./views/AboutView.vue') // Path to your component
);
</script>

<style scoped>
/* basic styles */
</style>
How it works: This snippet demonstrates how to lazy load a Vue 3 component using `defineAsyncComponent` and display a fallback state with `<Suspense>`. When `showAbout` becomes true, the `AboutView.vue` component is asynchronously loaded. This technique significantly reduces the initial JavaScript bundle size, leading to faster page loads and improved performance, especially beneficial for single-page applications with many routes or large, infrequently used components.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs