This time I will bring you the on-demand loading effect of react. What are the precautions for react to make on-demand loading effect? The following is a practical case, let's take a look.
Although I have been doing react-related optimizations, on-demand loading, dll separation, and server-side rendering, I have never started with routingcode splitting. Yesterday, I did it locally The test was not successful during development. I tried it again today and it has been deployed to the online environment. I will record this today.
Modify configuration
Development environment: webpack@v3, react-router@v4Installation dependencies:$ yarn add babel-plugin-syntax-dynamic-import -dev
Transform the project code
Installation dependencies:$ yarn add react-loadable
import React from 'react'; import { Icon } from 'antd'; const Loading = ({ pastDelay, timedOut, error }) => { if (pastDelay) { return <p><Icon type="loading" /></p>; } else if (timedOut) { return <p>Taking a long time...</p>; } else if (error) { return <p>Error!</p>; } return null; };
import React from 'react'; import Loadable from 'react-loadable'; import { Route, Switch } from 'react-router-dom'; const Home = Loadable({ loader: () => import('../Home'), loading: Loading, timeout: 10000 }); const EditArticle = Loadable({ loader: () => import('../EditArticle'), loading: Loading, timeout: 10000 }); ... <Switch> <Route exact path="/home" component={Home} /> <Route path="/editarticle" component={EditArticle} /> </Switch>
entry file app.js, and other scripts will access the corresponding The page will be loaded through this file.
Verification results
After uploading #It can be seen that the page script loaded when accessing the first page is only 21.8 after gzip compression. KB! ! ! Of course, this is also related to the complexity of the page, but compared with loading all scripts, it has been greatly reduced. This optimization is particularly obvious to users with highly targeted access. Another benefit of doing this is that when we only change the business code of some pages in the project, the code of other pages remains unchanged, so at this time other pages use client cache. Another level of optimization has been done.Tips
react-loadable also has other configuration options, which can be configured as needed; I believe you have mastered the method after reading the case in this article. For more exciting content, please pay attention to other related articles on the php Chinese website! Recommended reading:Detailed explanation of the use of the slot socket of the vue component
Detailed explanation of the use of JS origin policy for cross-domain access
The above is the detailed content of React makes on-demand loading effect. For more information, please follow other related articles on the PHP Chinese website!