React构建的JS优化思路

背景

之前个人博客搭建时,发现页面加载要5s才能完成并显示

问题

React生成的JS有1.4M,对于个人博客服务器的带宽来说,压力较大,因此耗费了5S的时间

优化思路

解决React生成的JS大小,因为我用的是react-router-dom路由模块,查阅资料发现可以利用懒加载的机制,实现JS分割成不同的JS文件

利用React.lazy进行懒加载,在页面尚未加载完毕的时候,需要配置Suspense

Suspense的作用是当React.lazy懒加载完成时,就回调真正的页面实现展示

实现代码

javascript 复制代码
import React, {Suspense } from 'react'
import { BrowserRouter, Route } from 'react-router-dom'
import { Loading } from '../components/common'

import Home from '../components'
import Download from '../components/download/'
import Login from '../components/login'
import Prize from '../components/prize'
import News from '../components/news'
import NewsDetail from '../components/news/detail'
import Support from '../components/support'
import Me from '../components/me'
import Pay from '../components/pay'

const App = () => (
  // 使用 BrowserRouter 的 basename 确保在服务器上也可以运行 basename 为服务器上面文件的路径
  <BrowserRouter basename='/'>
    <Route path='/' exact component={Home} />
    <Route path='/download' exact component={Download} />
    <Route path='/prize' exact component={Prize} />
    <Route path='/news' exact component={News} />
    <Route path='/news/detail' exact component={NewsDetail} />
    <Route path='/support' exact component={Support} />
    <Route path='/me' component={Me} />
    <Route path='/pay' component={Pay} />
    <Login />
  </BrowserRouter>
)

// 因为使用了多语言配置,react-i18next 邀请需要返回一个函数
export default function Main() {
  return (
    <Suspense fallback={<Loading />}>
      <App />
    </Suspense>
  );
}

优化后效果

参考文章

相关推荐
共享家952715 小时前
搭建 AI 聊天机器人:”我的人生我做主“
前端·javascript·css·python·pycharm·html·状态模式
Halo_tjn16 小时前
基于封装的专项 知识点
java·前端·python·算法
摘星编程17 小时前
OpenHarmony环境下React Native:自定义useTruncate文本截断
javascript·react native·react.js
Duang007_17 小时前
【LeetCodeHot100 超详细Agent启发版本】字母异位词分组 (Group Anagrams)
开发语言·javascript·人工智能·python
2601_9498683618 小时前
Flutter for OpenHarmony 电子合同签署App实战 - 主入口实现
开发语言·javascript·flutter
m0_7482299919 小时前
Vue2 vs Vue3:核心差异全解析
前端·javascript·vue.js
2601_9495936519 小时前
高级进阶React Native 鸿蒙跨平台开发:LinearGradient 背景渐变与主题切换
react native·react.js·harmonyos
C澒19 小时前
前端监控系统的最佳实践
前端·安全·运维开发
xiaoxue..19 小时前
React 手写实现的 KeepAlive 组件
前端·javascript·react.js·面试
摘星编程19 小时前
在OpenHarmony上用React Native:自定义useHighlight关键词高亮
javascript·react native·react.js