[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.
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步