Skip to content

懒加载组件

当打包构建应用时,Javascript 包会变得非常大,影响页面加载速度。如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就更加高效了。

结合 React 的 Suspenselazy 样例如下:

 




 
 
 
 
 
 
 
 
 






















 
 
 


 
 
 


 
 
 


 
 
 




 
 
 


 
 
 




 
 
 


 
 
 









import { Suspense, lazy } from 'react';
import { Col, Row } from 'antd';

import PageLoading from '@/components/PageLoading';

const ArticleChartCard = lazy(() => import('./components/ArticleChartCard'));
const WorksChartCard = lazy(() => import('./components/WorksChartCard'));
const TopicsChartCard = lazy(() => import('./components/TopicsChartCard'));
const LinksChartCard = lazy(() => import('./components/LinksChartCard'));

const HotSearchCard = lazy(() => import('./components/HotSearchCard'));
const HotTagsCard = lazy(() => import('./components/HotTagsCard'));
const ArticleHitCard = lazy(() => import('./components/ArticleHitCard'));
const WorksHitCard = lazy(() => import('./components/WorksHitCard'));

const ChartColProps = {
  xs: 24,
  sm: 12,
  md: 12,
  lg: 12,
  xl: 6,
};

const TableColProps = {
  xs: 24,
  sm: 24,
  md: 24,
  lg: 12,
  xl: 12,
};

function App() {
  return (
    <div className='layout-main-conent'>
      <Row gutter={24}>
        <Col {...ChartColProps}>
          <Suspense fallback={<PageLoading />}>
            <ArticleChartCard />
          </Suspense>
        </Col>
        <Col {...ChartColProps}>
          <Suspense fallback={<PageLoading />}>
            <WorksChartCard />
          </Suspense>
        </Col>
        <Col {...ChartColProps}>
          <Suspense fallback={<PageLoading />}>
            <TopicsChartCard />
          </Suspense>
        </Col>
        <Col {...ChartColProps}>
          <Suspense fallback={<PageLoading />}>
            <LinksChartCard />
          </Suspense>
        </Col>
      </Row>
      <Row gutter={24}>
        <Col {...TableColProps}>
          <Suspense fallback={<PageLoading />}>
            <HotSearchCard />
          </Suspense>
        </Col>
        <Col {...TableColProps}>
          <Suspense fallback={<PageLoading />}>
            <HotTagsCard />
          </Suspense>
        </Col>
      </Row>
      <Row gutter={24}>
        <Col {...TableColProps}>
          <Suspense fallback={<PageLoading />}>
            <ArticleHitCard />
          </Suspense>
        </Col>
        <Col {...TableColProps}>
          <Suspense fallback={<PageLoading />}>
            <WorksHitCard />
          </Suspense>
        </Col>
      </Row>
    </div>
  );
}

export default App;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

Released under the MIT License.