JAVASCRIPT

Lazy Load Vue 3 Components for Improved Performance

Optimize your Vue 3 application's performance by lazy loading components, reducing initial bundle size and improving page load times for better user experience.

// main.js or router/index.js (if used in routes)
import { createApp, defineAsyncComponent } from 'vue';
import App from './App.vue';
import router from './router'; // Assuming you have Vue Router setup

const app = createApp(App);

// Example of a lazy-loaded component directly in a component
// MyComponent.vue
// <template>
//   <Suspense>
//     <template #default>
//       <LazyLoadedContent />
//     </template>
//     <template #fallback>
//       <div>Loading...</div>
//     </template>
//   </Suspense>
// </template>
// <script setup>
// const LazyLoadedContent = defineAsyncComponent(() =>
//   import('./LazyLoadedContent.vue')
// );
// </script>

// Example of lazy-loaded routes in router/index.js
// const routes = [
//   {
//     path: '/admin',
//     name: 'admin',
//     component: () => import(/* webpackChunkName: "admin" */ '../views/AdminDashboard.vue')
//   },
//   {
//     path: '/user-profile',
//     name: 'profile',
//     component: () => import(/* webpackChunkName: "profile" */ '../views/UserProfile.vue')
//   }
// ];

app.use(router);
app.mount('#app');
How it works: This snippet illustrates how to lazy load Vue 3 components, either directly within another component using `defineAsyncComponent` and `Suspense`, or more commonly, by defining asynchronous route components in Vue Router. Lazy loading components means they are only loaded when they are actually needed, reducing the initial JavaScript bundle size and significantly improving the application's startup performance.

Need help integrating this into your project?

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

Hire DigitalCodeLabs