react 首屏載入優化
阿新 • • 發佈:2018-10-31
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;
具體配置截圖為: