Lazy loading is a powerful technique where a JavaScript module, component, or chunk is not loaded upfront. Instead, it's fetched from the server only when needed.
Why Lazy Loading?
Let’s say a user visits your website and requests a specific URL. Your server responds with the main JavaScript file (main.js), which is then downloaded by the browser.
But here’s the question:
Should main.js include all components in your application?
Not really. If you include everything in one file, the file size becomes large, leading to longer load times and a
slower user experience.
The Solution: Lazy Loading
You can lazy load components that are not needed immediately—such as those that appear after scrolling or on specific interactions. This way, only the essential parts are loaded at first, and the rest are fetched on demand.
How to Implement Lazy Loading in Vue 3
import { defineAsyncComponent } from 'vue'
const LazyComponent = defineAsyncComponent(() => import('./BigComponent.vue'))
Here, the dynamic import() tells your bundler (like Webpack or Vite) to separate this component into a new JavaScript chunk, instead of bundling it with the main file.
What is a "Chunk"?
Assume you have 5 large components in your app. If all are bundled together, your main.js might become 1MB+ in size.
But with lazy loading:
- main.js could stay small (e.g., 400KB),
- Other components load as separate chunks when needed:
main.js
LazyComponent.123abc.js (200KB)
AnotherComponent.xyz456.js (300KB)
What Happens During Lazy Load?
When the user first lands on your page, only main.js is loaded. If they scroll down and a lazy-loaded component is required, Vue fetches the corresponding JavaScript chunk asynchronously and loads it into the browser.
Enter <Suspense>
Since lazy-loaded components are asynchronous, there can be a slight delay while they load. If you don’t show anything during that time, users might get confused or feel the page is broken.
Vue 3 solves this using the component. It allows you to show a fallback UI (like a loading spinner or skeleton) while the component is being fetched.
<Suspense>
<template #default>
<LazyComponent />
</template>
<template #fallback>
<LoadingSpinner />
</template>
</Suspense>
🌟Benefits of Using Lazy Loading with Suspense
- Smoother loading experience for users.
- Only loads components when necessary, reducing initial load size.
- Faster page rendering and better performance.
- Users see a visual indicator (like a spinner or skeleton) while content loads.
Top comments (0)