React优化首屏加载时间之异步加载

首屏白屏时间过长一直是前端优化的主要内容之一,此次优化采用了异步加载的方法。也就是用户输入网址进入首页的时候,只加载首页内容。其他页面等用户进入的时候再加载。

异步加载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//异步组件
import React, { Component } from 'react';
export default function asyncComponent(importComponent) {
class AsyncComponent extends Component {
constructor(props) {
super(props);
this.state = {
component: null,
};
}
async componentDidMount() {
const { default: component } = await importComponent();
this.setState({
component: component,
});
}
render() {
const C = this.state.component;
return C ? <C {...this.props} /> : null;
}
}
return AsyncComponent;
}
1
2
3
4
5
6
7
8
9
10
11
12
// app.js
import asyncComponent from '@/components/AsyncComponent';
const AsyncMain = asyncComponent(() => import('./Main'));
const AsyncChildA = asyncComponent(() => import('./ChildA'));
const AsyncChildB = asyncComponent(() => import('./ChildB'));
const AsyncChildC = asyncComponent(() => import('./ChildC'));
<Switch>
{<Route exact path="/main" component={AsyncMain} />}
{<Route exact path="/childa" component={AsyncChildA} />}
{<Route exact path="/childb" component={AsyncChildB} />}
{<Route exact path="/childc" component={AsyncChildC} />}
</Switch>;
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2018-2020 Jee
  • Visitors: | Views:

如果您觉得此文章帮助到了您,请作者喝杯咖啡吧~

支付宝
微信