Async Components
When developing with a framework, you can find yourself having a lot of components for your user interface.
Loading all the components on the server can take time. Luckily, Vue offers us a way to only load components when needed.
The best of example of this would be a modal component. Usually, a modal is only loaded when something on the page is clicked. Click the search bar on the top bar (above this article) to see and example of a modal popup.
Create Async Component
Unless the component is made into an async component, that modal will be loaded when navigating to that page. We can prevent it from being loaded immediately and to only load when it is needed by making it async:
const SearchModal = defineAsyncComponent(() => import("~/components/documentation/searchModal.vue"));
You can also define this component globally:
app.component("SearchModal", defineAsyncComponent(() => import("./components/documentation/searchModal.vue")));
Check loaded components
Use the network tab of your browser's developer tools to track which components are taking a long time to load:
The tab network is highlighted in the image along with name and time. The name will show you the name of what is being loaded and the time will show you, usually in milliseconds, how long it takes to load that file/component.
Async Component Options
loadingComponent - add a component to be shown while loading
delay - a delay before showing the loading component (prevents flicker, default is 200ms)
errorComponent - add a component to be shown when an error occurs
timeout - the time given until catching an error
const SearchModal = defineAsyncComponent({ loader: () => import("~/components/documentation/searchModal.vue"), loadingComponent: loadingSpinner, delay: 200, errorComponent: showErrorBox, timeout: 4000});
In the example above, the loader begins loading the SearchModal component. In the meantime, after 200ms, the loadingSpinner shows while loading occurs. If after 4000ms the component still does not load, the showErrorBox component will show.