loading...
Cover image for Lazy loading in Vue

Lazy loading in Vue

reiallenramos profile image Rei Allen Ramos ・2 min read

Today I was browsing Vue resources and stumbled upon Webpack's code splitting feature. Several links later, I found this video that demonstrates how seamless it can be done in Vue.

Webpack's Code splitting

Code splitting is the practice of bundling javascript files into small chunks. Lazy loading refers to how Webpack serves these chunks only when needed. When done correctly, they alleviate page loading time.

Example

For a given routes.js:

import Home from './components/Home.vue'
import MyProfile from './components/MyProfile.vue'
import About from './components/About.vue'

const routes = [
  {
    path: "/",
    name: "home",
    component: Home
  },
  {
    path: "/myProfile",
    name: "myProfile",
    component: MyProfile
  },
  {
    path: "/about",
    name: "about",
    component: About
  }
]

export default routes;

This is most likely how your basics-to-vue-router tutorial has introduced routing and there's nothing wrong with it! However, we have Webpack at our disposal so let's use it to the fullest. Time to level up!

Lazy loading in Vue is literally just one line. Let's take "/myProfile" route and lazy load it by simply modifying the component property and converting it to an arrow function that imports the, err, component.

// before
component: MyProfile

// after
component: () => import( "./components/MyProfile.vue" )

Hooray! 🎉 Another fancy term for this is dynamic imports. Behind the scenes, when we visit the root route "/home", Webpack served a bundled app.js file but set aside MyProfile.vue for later use. When the user visits "/myProfile" route, that's Webpack's cue to serve it.

Let's lazy load /about route too. The final routes.js should look like:

import Home from './components/Home.vue'

const routes = [
  {
    path: "/",
    name: "home",
    component: Home
  },
  {
    path: "/myProfile",
    name: "myProfile",
    component: () => import( "./components/MyProfile.vue" )
  },
  {
    path: "/about",
    name: "about",
    component: () => import( "./components/About.vue" )
  }
]

export default routes;

I hope you noticed that we didn't lazy load the Home component because it defeats the purpose of code splitting. As a general rule of thumb, lazy load components that aren't needed on the landing page.

Posted on by:

reiallenramos profile

Rei Allen Ramos

@reiallenramos

Ruby/Ember dev learning to blog. Writing simple and straight-to-the-point tutorials!

Discussion

pic
Editor guide