react項目 性能優化 首頁優化 加載優化


react路由懶加載(異步組件)------react-loadable(以路由組件分割代碼) 或者參考 https://www.cnblogs.com/SRH151219/p/11207919.html

安裝

cnpm install react-loadable -S

  

如果項目有100個頁面,那laodable.js就需要寫100遍,這樣就感覺有點冗余了,所以這個我們可以封裝一下

首先,我們建一個util    src/util/loadable.js

import React from 'react';
import Loadable from 'react-loadable';
import { Spin } from 'antd';
//通用的過場組件
function loadingComponent() {
  return (
    <div style={{
      display: "flex",
      justifyContent: "center",
      alignItems: "center",
      textAlign: 'center',
      width: "100%",
      height: "1000px"
    }}> <Spin size="large" /></div >
  )
}

//過場組件默認采用通用的,若傳入了loading,則采用傳入的過場組件
export default (loader, loading = loadingComponent) => {
  return Loadable({
    loader,
    loading
  });
}

不難看出,我們可以將按需加載的組件和過渡組件通過參數傳入最后返回包裝后的組件,

router里面調用方式改為如下

import React, { Fragment } from 'react'
import { BrowserRouter, Route } from 'react-router-dom'
import loadable from '../util/loadable'

const Home = loadable(()=>import('@pages/home'))

const Routes = () => (
    <BrowserRouter>
        <Route path="/home" component={Home}/>
    </BrowserRouter>
);

export default Routes

react-loadable是以組件級別來分割代碼的,這意味着,我們不僅可以根據路由按需加載,還可以根據組件按需加載,使用方式和路由分割一樣,只用修改組件的引入方式即可

 

Create-React-app項目首屏加載優化(二)--CDN加速  參考https://www.cnblogs.com/njuclc/p/13359388.html

 

React 16 加載性能優化指南

https://www.jianshu.com/p/d7c30b590f8a

 

Webpack nginx gzip實現前端加載優化 參考 https://www.cnblogs.com/njuclc/p/12883661.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM