Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lazy load a plugin in Vue?

Tags:

vue.js

Vue plugins usually requires a global setup in app entrypoint by Vue.use(somePlugin). Doing so increases the bundle size for all pages, which is often bad and that it is better to defer the downloading of the module until when the module is actually being used, aka lazy loading or code spliting.

How do I lazy load a plugin if only one page in my Vue app needs it?

like image 829
golopot Avatar asked Apr 29 '19 03:04

golopot


People also ask

How do you use lazy loading at Vue?

vue file. Lazy loading refers to an approach by which all the scripts are not loaded on the DOM as the application starts. Instead, they're only loaded when requested, which makes the JavaScript bundle size very small at initial load. Vue.

What is lazy load plugin?

Lazy Load by WP is an extremely lightweight plugin developed by the well-known WP Rocket cache plugin (Yup, this is us!). It is one of the most popular tools which helps you make your pictures and videos visible to the visitors only when they are right above the fold.


1 Answers

To answer the OP's question more directly: You can't lazy load a plugin.

According to the documentation, plugins by definition provide globally-accessible functionality and must be setup with Vue.use() before the Vue instance is created. Due to this, they'll always be bundled with the entire Vue instance (in a vendors chunk, for example).

What you want is to lazy load the functionality in a smaller scope, at a component level. Depending on the plugin, the plugin module should also support some sort of direct code importing at a component level, like this one does. Because it just uses import statements, they can be async loaded.

TL;DR: Anything using Vue.use() can't be lazy loaded. Async imports can.

like image 119
tryforceful Avatar answered Nov 09 '22 14:11

tryforceful