Academind Logo
Implementing Lazy Loading in Vue Apps

Implementing Lazy Loading in Vue Apps

Lazy loading can speed up the initial loading time of your Vue app, hence it's an important optimization. Here's how to use it correctly.

Created by Maximilian Schwarzmüller

Lazy loading is an important concept in modern web apps - see my dedicated tutorial for more information about the general idea behind lazy loading.

To sum it up: Lazy loading allows us to load resources like scripts and images "just in time", i.e. only when they're really needed. This can reduce the initial page loading time and also save bandwidth for your users.

In Vue apps image lazy loading works just as explained in the above article, there's no Vue-specific implementation of it.

But when it comes to lazy loading script code, there is a difference. You don't need to write your own lazy loading code for that - at least not the code shown in the linked article.


Which Scripts Can You Load Lazily?

In Vue apps, you of course write a lot of script code - you're working with tons of components after all (and context, hooks etc).

There are two main kinds of code that you can load lazily in component-focused web apps like the ones you're building with Vue:

  • Components: Only load component code (and all related code) when a component is rendered to the screen

  • Routes: Only load route component code (and all related code) when a route is visited by the user


How To Add Lazy Loading

Both is implemented in the same way: With async components.

Here's how you define a component as "to be lazy loaded":

components: {
'user-profile': () => import('./user-profile/UserProfile');

You use this lazy loaded component just like any other component:

<div v-if="someCondition">

For routing, it's quite similar:

const router = new VueRouter({
routes: [
path: '/user-profile',
component: () => import('./user-profile/UserProfile'),

All the rest is handled by Vue and the underlying build workflow tool (e.g. Webpack) - you don't need to do anything else!

Recommended Courses