[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  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
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
点击右上角即可分享
微信分享提示