react 首屏加载优化
react 首屏加载优化,原本是在入口HTML文件中加载loading动画,但是部署在测试环境上的时候一直无法显示loading的部分,也是奇怪了,我们测试环境的部署一直跟本地的都不太一样,内外网的转发多次,总感觉会丢掉一些文件。
本次采取的优化方法就是,按需加载,首先需要下载依赖,yarn add react-loadable, index.js页面代码如下:
import React from 'react'; import ReactDOM from 'react-dom'; import { Switch, HashRouter, Route } from 'react-router-dom'; import Loadable from 'react-loadable' import Loading from './component/common/loading' // import './App.css'; import './index.css'; import registerServiceWorker from './registerServiceWorker'; // import Main from './component/main/main' let Main = Loadable({ loader:()=>import('./component/main/main'), loading: Loading }) let Question = Loadable({ loader:()=> import('./component/question/question'), loading: Loading }) let Egg = Loadable({ loader:()=> import('./component/egg/egg'), loading: Loading }) let Result = Loadable({ loader:()=> import('./component/result/result'), loading: Loading }) let Email = Loadable({ loader:()=> import('./component/email/email'), loading: Loading }) // import Question from './component/question/question' // import Egg from './component/egg/egg' // import Result from './component/result/result' // import Email from './component/email/email' // document.onreadystatechange = function listen(){ // if(document.readyState == 'complete'){ // ReactDOM.render( // <div className="App"> // <HashRouter> // <Switch> // <Route exact path="/" component={Main}/> // <Route exact path="/question" component={Question}/> // <Route exact path="/egg/:kyc" component={Egg}/> // <Route exact path="/result" component={Result}/> // <Route exact path="/email" component={Email}/> // </Switch> // </HashRouter> // </div>, // document.getElementById('root')); // }else{ // ReactDOM.render( // <div style={{fontSize:'40px',color:'#000'}}> // loading // </div>, // document.getElementById('root')); // } // } // document.onreadystatechange = listen ReactDOM.render( <div className="App"> <HashRouter> <Switch> <Route exact path="/" component={Main}/> <Route exact path="/question" component={Question}/> <Route exact path="/egg/:kyc" component={Egg}/> <Route exact path="/result" component={Result}/> <Route exact path="/email" component={Email}/> </Switch> </HashRouter> </div>, document.getElementById('root')); registerServiceWorker();
本次的css文件同样也是很大,采取的原则就是拆分开各个css文件,不同的组件再引入需要的css,前面页面已经引入的css文件后面不需要再引入
2.nginx 开启gzip,亲测试开启之后压缩了很多,截图如下:
css,js文件压缩来超过一半,
具体是在nginx的配置文件中下面配置文件:
gzip on;
gzip_buffers 32 4k;
gzip_comp_level 6;
gzip_min_length 200;
gzip_types text/css text/xml application/javascript;
gzip_vary on;
具体配置截图为: