Nuxt.js: How to lazy load components?

Created on 23 Mar 2018  路  11Comments  路  Source: nuxt/nuxt.js

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?

This question is available on Nuxt.js community (#c2698)

Most helpful comment

@jerakode Yup, it is :)

All 11 comments

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

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?

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.

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.

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

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

@jerakode Yup, it is :)

@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

@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.

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.

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vadimsg picture vadimsg  路  3Comments

gary149 picture gary149  路  3Comments

VincentLoy picture VincentLoy  路  3Comments

pehbehbeh picture pehbehbeh  路  3Comments

msudgh picture msudgh  路  3Comments