bg-img

    Created by Maximilian Schwarzmüller
    Last Updated on June 19, 2020

    Implementing Lazy Loading in Vue Apps

    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.

    Learn more about lazy loading and Vue in general in my Vue.js - The Complete Guide course.

    # 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">
      <user-profile></user-profile>
    </div>

    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!