Jon Sud
Jon Sud

Reputation: 11641

vue and webpack doesn't do lazy loading in components?

The lazy component in vue/webpack seem to be wrong or I miss confuse about the terms.

To do lazy loading of component I use the keyword import and webpack should split this component to sepeate bundle, and when I need to load this component webpack should take care of it and load the component.

but in fact, webpack does make sperate file, but it loaded anyway when the application is running. which is unexpected.

enter image description here

For example I just create a simple vue application (using the cli) and browse to localhost:8080/ and the about page should be loaded (by default) using the import keyword.

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    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')
  }
]

So This is by design? I load every time the file I do not need right now (the page about). and if I have 200 pages, when I'll fetch 200 files I dont need. how that ends up? that did I save here by using the import key?

In vuetify for example they uses import key, but the files are loaded anyway and not by demand.

Upvotes: 2

Views: 2474

Answers (3)

achwilko
achwilko

Reputation: 804

You can also avoid component prefetch using one of the webpack "magic" comments (https://webpack.js.org/guides/code-splitting/#prefetchingpreloading-modules), eg.

components: {
  MyComponent: () => import(/* webpackPrefetch: false */ './MyComponent.vue')
}

Feel free to read more about this Vue optimization below:

https://vueschool.io/articles/vuejs-tutorials/lazy-loading-individual-vue-components-and-prefetching/

Upvotes: 4

Anant Vikram Singh
Anant Vikram Singh

Reputation: 558

try using vue-lazyload maybe it can help and for <script> tags you can try async defer it helps in website speed optimizations

Upvotes: 1

tony19
tony19

Reputation: 138316

If you're referring to the default app template from Vue CLI, then you're actually observing the prefetch of the About page, intended to reduce load times for pages the user will likely visit.

If you want to avoid this performance optimization, use this Vue config:

// vue.config.js
module.exports = {
  chainWebpack: config => {
    config.plugins.delete('prefetch')
    config.plugins.delete('preload')
  }
}

For troubleshooting reference, Chrome's Network panel includes an Initiator column, which provides a clickable link to the source file that triggered the network call. In this case of the about.js, the source file looks like this:

screenshot

Upvotes: 2

Related Questions