How to use react-loadable to optimize slow page loading

Background: The company just took over the project. The first task my brother gave me was to optimize the page loading speed. Every time I opened a page, it was too slow, so I started to do that.

This is mainly used herereact-loadable

Install NPM I react-loadable --saveCopy the code

The main thing is to load routes on demand and then achieve page acceleration.

Step 1: Write one of our higher-order components

//loadable.jsx
import React from 'react';
import Loadable from 'react-loadable';
 
import {Card} from 'antd';
// Load components as needed
export default function withLoadable (comp) {
    return Loadable({
        loader:comp,
        loading:(props) = >{
            if (props.error) {
                return <Card style={{width:"100% ",height:"100%"}} >Loading error. Please refresh</Card>;
            } else if (props.timedOut) {
                return <Card style={{width:"100% ",height:"100%"}} >Loading timed out. Please refresh</Card>;
            } else if (props.pastDelay) {
                return <Card loading={true} style={{width:"100% ",height:"100%}} "/ >;
            } else {
                return null; }},timeout:10000})}Copy the code

Step two: Transform our routing

import React from 'react';
// Introduce the higher-order component we wrote in the first step
import Loadable from '@/components/loadable/index';
import { Route, IndexRedirect } from 'react-router';

//import HomePage from '@/containers/homePage';
// Wrap our previous component in a higher-order component and return
const HomePage = Loadable(() = > import('@/containers/homePage'));

export default (
    <div>
        <Route path="homePageOld" component={HomePage} />
    </div>
)
Copy the code

In this way, you will find that the component is imported only if the route matches, which is achievedcode splittingThe effect of “load on demand” is often referred to as “chunking” code, rather than loading all the components at the beginning. That’s OK, that’s comfortable for my project. You can try it.

Emphasis the import ()

Don’t put theimportKey words andimport()Method confused, which was introduced for dynamic loading.

The import keyword is statically compiled and promoted, which is against loading on demand, hence import(), whereas react-loadable uses import() for dynamic loading.