[Vue Router] Lazy loading routes

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.

posted @   Zhentiw  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Deepseek官网太卡,教你白嫖阿里云的Deepseek-R1满血版
· 2分钟学会 DeepSeek API,竟然比官方更好用!
· .NET 使用 DeepSeek R1 开发智能 AI 客户端
· DeepSeek本地性能调优
· autohue.js:让你的图片和背景融为一体,绝了!
历史上的今天:
2022-11-26 [XState] raise event: trigger an action immediately when reach target state
2022-11-26 [Typescript] 118. Hard - IsRequiredKey
2022-11-26 [Typescript] 117. Hard - ClassPublicKeys
2020-11-26 [RxJS] Filtering operator: first
2020-11-26 [Tools] Interactively exploring a large JSON file with fx
2020-11-26 [Javascript] Broadcaster + Operator + Listener pattern -- 22. mapError, wrap fetch with broadcaster with cancellation
2020-11-26 [Javascript] Cancel a promise
点击右上角即可分享
微信分享提示