How to lazy load components?

jerakode
8
jerakode
commented a year ago

Hello. I have admin route where I have big Component that uses few external libraries. This route will be avaliable only for me, not for users of my site. RIght now it's loaded from the start even if I on another route.

I tried this

const vue2Dropzone = () => import('vue2-dropzone')
components: {
    vueDropzone: vue2Dropzone
  }

But still chunk is loaded even if I am not on this route. What is the logic behinfd this? How to actually load code only when I need it? Why it is not working out of the box?

0
manniL
5.8k
manniL
commented a year ago

It's likely preloaded, which is a benefit rather than a disadvantage. That means that components for the current route are loaded first, then the other components will be preloaded/prefetched.

But you can disable that behavior if you need to.

Code splitting and lazy loading already work out of the box as you described it.

Related: #1838

0
jerakode
8
jerakode
commented a year ago

No, I don't see such behavior in my example. I doesn't preloaded, it's fully loaded, even if I don't need it. All my users don't need this chunk, why should I preload it? Only me, admin will use it. Right now it's fully loaded on another routes. Why? Is it normal behavior?

0
manniL
5.8k
manniL
commented a year ago

As I mentioned above, it will be loaded after the components needed for the current route. This is the default behavior. I've linked you an issue above that should be related to your use case.

0
manniL
5.8k
manniL
commented a year ago

After digging deeper and trying several approaches, the one mentioned in https://github.com/nuxt/nuxt.js/issues/1838#issuecomment-337064976 works quite well. The admin chunks will only be loaded when you visit the page and your main users won't have to download them.

0
jerakode
8
jerakode
commented a year ago

I just tried this. Don't see any changes. All is loaded on any page.

0
jerakode
8
jerakode
commented a year ago

Oh, my bad. I clicked wrong thing in DevTools. It's working! So this is basically is solution, right?

0
manniL
5.8k
manniL
commented a year ago

@jerakode Yup, it is :)

0
johnyluyte
0
johnyluyte
commented a year ago

@manniL Dose the "preloaded" feature you mentioned here only works in Nuxt Universal mode? I am using Nuxt SPA mode and I don't see things being prefetched. Is it a SSR only feature? Thanks

0
manniL
5.8k
manniL
commented a year ago

@johnyluyte Yes, this only works in SSR mode currently. With edge (Nuxt 2.0) this will work in SPA as well but is disabled by default everywhere.

0
Jones-S
3
Jones-S
commented a year ago

I think vue-lazyload supports lazyloading of components as well:
https://github.com/hilongjw/vue-lazyload#lazy-component
Haven't tried it, but may be worth a shot.

0
Informations
Question โ€ข Unresolved
#c2698 - Created a year ago