Lazy loading components is a easy way to improve the user experience of your app especially if your code bundle is big or if users are on slow connections.
Vue 3 has introduced several new features to help you achieve this easily and with great UX through the improvements to the async component API and the new Suspense
component.
Some parts of your UI don’t need to be loaded the instant a user visits your app, for example, dynamic UI features like modals and tooltips, etc. And, if you’re using the single-page app architecture, page content on unseen pages shouldn’t be loaded until needed either.
You can get an easy performance win by “lazy loading” the components that contain such features and content. This means the code for these components is not included in the initial code bundle sent to a user and is instead loaded on demand.
In this example app, our app displays a component ChatWindow
which loads if the user is authenticated.
The details aren’t important, but let’s assume authentication can only be determined at runtime, and that this component is big and bulky. For these reasons, we may want to lazy load it.
App.vue
<template>
<h3>Chat with friends here</h3>
<chat-window v-if="auth" />
</template>
<script>
import ChatWindow from "@/components/ChatWindow";
export default {
components: {
ChatWindow
},
...
}
</script>
Vue 3 has introduced the defineAsyncComponent
API which makes it very simple to lazy load a component.
All you need to do is pass a function to the constructor that loads your component. Assuming you’re bundling your code with Webpack or something similar, the easiest way to do this is to use the dynamic import feature (import
) which will ensure your component is built into a separate file and loaded only when called upon.
<script>
import { defineAsyncComponent } from "vue";
const ChatWindow = defineAsyncComponent(
() => import("@/components/ChatWindow")
);
export default {
components: {
ChatWindow
},
...
}
</script>
When this app is built, you’ll see any dynamically imported component as a separate file in your build.
File Size
dist/js/chunk-vendors.f11402df.js 82.39 KiB
dist/js/app.ada103fb.js 20.59 KiB
dist/js/ChatWindow.3c1708e4.js 5.47 KiB
dist/css/app.8221c481.css 1.76 KiB
dist/css/ChatWindow.f16731cd.css 2.75 KiB
For more info on how this works, see my previous article Code Splitting With Vue.js And Webpack.
#vue.js #components #web performance #vue #vue 3 #programming