JAVASCRIPT
Lazy Load Vue 3 Components for Performance
Improve Vue 3 application performance by asynchronously loading components only when needed, reducing initial bundle size and speeding up page load times.
import { defineAsyncComponent } from 'vue';
// Define an async component
const MyAsyncComponent = defineAsyncComponent(() =>
import('./MyComponent.vue')
);
// Example usage in a parent component
<template>
<div>
<h1>Parent Component</h1>
<!-- The component will be loaded only when MyAsyncComponent is mounted -->
<MyAsyncComponent />
</div>
</template>
<script setup>
import MyAsyncComponent from './MyAsyncComponent.vue'; // The actual path to your async component
</script>
How it works: This snippet demonstrates how to lazy load components in Vue 3 using `defineAsyncComponent`. Instead of bundling all components upfront, `defineAsyncComponent` allows you to defer the loading of a component until it's actually rendered on the page. This technique significantly reduces the initial JavaScript bundle size, leading to faster page load times and improved application performance, especially for larger applications with many routes or conditionally rendered components.