Lazy loading in Vuejs uses Webpack code splitting

Tram Ho

Introduce

I think you guys here have certainly heard these two terms at least once “code splitting” and “lazy loading” . Let’s take a look to see how webpack defines these terms:

Lazy, or “on demand”, loading is a great way to optimize your site or application. This practice essentially involves splitting your code at logical breakpoints, and then loading it once the user has done something that requires, or will require, a new block of code. This speeds up the initial load of the application and lightens its overall weight as some blocks may never even be loaded.

Provisional translation is

Slow loading, or “dependent loading,” is a great way to optimize your site or application. These two approaches basically involve splitting your code at logical stops, and then loading it after the user has done something that requires or will request a new block of code. This increases the initial loading speed of the application and lightens its overall weight as some blocks of code may never even be loaded.

Coding

Whenever possible I recommend using dynamic imports. Components will load in a lazy load fashion (by webpack) when needed.

Explain

When using Webpack to package your application, you can use different ways to work with modules (ES Modules, CJS, AMD …). If you choose the ESM way (recommended), you will have this type of syntax:

Use cases

Applicable circumstances

  1. Lazy load in component

By importing an arrow function, Vue will load this component when requested, at that time.

If the imported component uses named export, you can use the object returned from Promise. For example with the UiAlert component

  1. Lazy load in Vue router

Vue router built-in lazy loading

  1. Lazy load in Vuex module

Vuex has a registerModule method that allows us to automatically create Vuex modules. If the import returns a Promise with the parameter ES Module, we can use lazy load

Result

References

https://vuedose.tips/tips/dynamic-imports-in-vue-js-for-better-performance/

Good luck. Happy coding and peace out ✌️

Share the news now

Source : Viblo