异步组件

异步组件与代码分割

代码分割的作用,这里借用 webpack 官网的一段话:

Code splitting is one of the most compelling features of webpack. This feature allows you to split your code into various bundles which can then be loaded on demand or in parallel. It can be used to achieve smaller bundles and control resource load prioritization which, if used correctly, can have a major impact on load time.

至于异步组件

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 makes the lightens its overall weight as some blocks may never even be loaded.

根本原理是,将分割的代码通过动态加载script 的 src 方法 将js 代码在之后注入到页面.

好消息是, Webpack 帮我们做了这一步,我们只需要用 ES7 的 import() 方法即可做到.

需要注意的是, 结合动态组件一起使用.

主要的方法是通过 import()结合动态组件

code demo

<template>
<div class="app-content" @click="getAsyncComponent">
<component :is="placeholder"></component>
</div>
</template>
<script>
import LoadComp from './loading-comp'
export default {
data () {
return {
placeholder: LoadComp
}
},
methods: {
getAsyncComponent () {
if (this.placeholder === LoadComp) {
if (!this.ImgContent) {
this.ImgContent = () => import('./img-content.vue')
}
this.ImgContent().then((theComponent) => {
this.placeholder = theComponent.default
})
}
}
}
}
</script>






code source: https://github.com/wagnlinzh/async-component






by wanglinzhizhi