Home >Web Front-end >JS Tutorial >About Vue code splitting and lazy loading
Lazy loading is also called delayed loading, which means loading when needed and loading as needed. This article mainly introduces you to the implementation method of Vue code segmentation and lazy loading. The article introduces it in great detail through example code. It has certain reference learning value for everyone's study or work. Friends who need it will follow the editor to learn together. Study it. Hope it helps everyone.
Why lazy loading is needed
In a single-page application, if there is no application lazy loading, the file packaged with webpack will be abnormally large, resulting in too much content to be loaded when entering the homepage. If there are too many, the delay is too long, which is not conducive to the user experience. Using lazy loading can divide the page and load the page when needed, which can effectively share the loading pressure on the homepage and reduce the loading time of the homepage
How to cooperate with webpack to implement lazy loading of components
1. Configure the chunkFilename attribute in the output path in the webpack configuration file
output: { path: resolve(__dirname, 'dist'), filename: options.dev ? '[name].js' : '[name].js?[chunkhash]', chunkFilename: 'chunk[id].js?[chunkhash]', publicPath: options.dev ? '/assets/' : publicPath },
The chunkFilename path will be used as the path for lazy loading of components
2. Cooperate with the asynchronous loading method supported by webpack
resolve => require([URL], resolve), good support
npm install --save-dev babel-core babel-loader babel-plugin-syntax-dynamic-import babel-preset-es2015
use: [{ loader: 'babel-loader', options: { presets: [['es2015', {modules: false}]], plugins: ['syntax-dynamic-import'] } }]IntroductionIn the era of webpack > 2, vue It is easier to do code splitting and lazy loading. No loader or require.ensure is required.
//全局组件 Vue.component('AsyncComponent', () => import('./AsyncComponent')) //局部注册组件 new Vue({ // ... components: { 'AsyncComponent': () => import('./AsyncComponent') } }) // 如果不是default导出的模块 new Vue({ // ... components: { 'AsyncComponent': () => import('./AsyncComponent').then({ AsyncComponent }) => AsyncComponent } })Routing level code splitting
const AsyncComponent= () => import('./AsyncComponent') new VueRouter({ routes: [ { path: '/test', component: AsyncComponent} ] })Vuex module code segmentation, there is a dynamic registration module method in vuex, and import
const store = new Vuex.Store() import('./store/test').then(testModule => { store.registerModule('test', testModule) })Summary
Steps to implement lazy loading and cross-domain implementation using Js
Introduction to the lazy loading method of images in JavaScript
Lazy loading problem of pictures
The above is the detailed content of About Vue code splitting and lazy loading. For more information, please follow other related articles on the PHP Chinese website!