[Vue Router] Lazy loading routes

Zhentiw發表於2024-11-26

Lazy Loading Routes

When building apps that contain large amounts of JavaScript, the initial page load (where that JavaScript is downloaded) might start to get large and slow down how fast the application loads. There might also be parts of your application that are only loaded by certain people, such as content creators vs content consumers. There are a lot more people on YouTube who just watch videos vs create videos. The people who just watch videos don’t need to download all the JavaScript needed to load the web pages that video creators use.

Lazy Loading allows us to separate our application into separate JavaScript bundles, so that a bundle is only downloaded when needed.

You might have already seen the basic version of lazy loading when you created your first Vue application. The Vue Router by default contained this:

📃 /src/router/index.js

{
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }

If we load up the basic webpage, and look in Chrome Dev Tools Network tab, we can see that it’s not until we click the “about” link, that the about page JavaScript is loaded.

Another way we might often see the above code written in Vue is as such:

const About = () => import(/* webpackChunkName: "about" */ '../views/About.vue')

const routes = [
  ...
  {
    path: '/about',
    name: 'About',
    component: About
  }

As you might imagine, if you had a bunch of YouTube creator pages, you’d use the same webpackChunkName, like so:

const Uploader = () => import(/* webpackChunkName: "creator" */ '../views/Uploader.vue')
const Editor = () => import(/* webpackChunkName: "creator" */ '../views/Editor.vue')
const Publisher = () => import(/* webpackChunkName: "creator" */ '../views/Publisher.vue')

Now when any of those routes are navigated to, the creator.js JavaScript bundle is loaded onto the page.

相關文章