Watch the full presentation on Vue Mastery.
This is a simple demo showing how to:
- Lazy Load Components in Vue 2
- Lazy Load Routes in Vue 2
Bonus: vue.config.js shows how to split out vendor's chunk
In the /views/home.vue component, Bella is shown by default so we can lazy load the Daisy component since it's not visible on the initial page load.
What to Lazy Load? Anything that isn't visible on initial page load. (using v-if)
- Tabs (other than the default)
- Side Panel
- Modals
In the /router/index.js, the About page is already lazy loaded.
Typcially, there's not much value in lazy loading the home page, since it is the entry point of the application. If you have multiple entry points, then you may want to lazy load those.
To Lazy Load the Bella and Daisy routes, just change the import to a dynamic import. Change this:
import Bella from '@/components/bella'
to this:
const Bella = () => import('@/components/bella')
- Babel.config.js must have comments to true for this to work.
- Add the webpack magic comment to the dynamic import
const Bella = () => import(/*webpackChunkName: "dogs" */ '@/components/bella')
npm install
npm run dev
npm run build
npm run lint