Eager delay spinners are not a good user experience as they can make a snappy user interface feel slower. We can provide a better user experience (UX) by delaying spinners to appear only after a perceivable delay.
To achieve this improved UX, you can use AsyncComponent.
Vue provides the defineAsyncComponent
function to lazy load components:
defineAsyncComponent
accepts a loader function that returns a Promise. The resolve
callback should be called if the component has been loaded, and the reject
callback to indicate that loading the component has failed.
Now let's implement the delayed loading spinner by using the advanced options of the defineAsyncComponent
function:
This demo simulates a network request to fetch HelloWorld.vue
from a server which takes 2 seconds:
The loading component Loading.vue
is shown after a delay of 500ms, defined with delay: 500
.
You can try it yourself in this StackBlitz playground:
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Check if Slot Is Empty
You can check if a slot is empty, for example, only to render it if it has content.
Vue Tip: Avoid Empty Wrapper for Conditions
There are many situations when you need to conditionally display multiple Vue components. To avoid "empty" wrappers you should use not use HTML tags.