代码位置优化


1.不阻塞html解析,尽早下载
2.防止被外部JS阻塞


1.可直接访问DOM,无需监听DOM Ready
2.避免阻塞html解析

代码拆分

main.aaa.js → main.bbb.js
1MB更改会重新下载

JS

  1. runtime-xxx.js
  2. rendor-xxx.js
  3. common-xxx.js
  4. page-index-xxx.js

CSS

  1. reset.normolize.css
  2. rendor-xxx.css
  3. common-xxx.css
  4. page-admin-xxx.css

JS动态导入

  1. const array=[1,2,3]
  2. import('lodash').then( _ =>{
  3. const clone = _.cloneDeep(array)
  4. })

Vue动态导入

  1. const router = new VueRouter({
  2. routes:[
  3. {path:'/home',component:()=>import('./Home.vue')},
  4. {path:'/about',component:()=>({
  5. component:import('./About.vue'),
  6. loading:LoadingComponent,
  7. error:ErrorComponent,
  8. })}
  9. ]
  10. })

React动态导入

  1. import React, { Suspense, lazy } from 'react'
  2. import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
  3. const Home = lazy(() => import('./routes/Home'))
  4. const About = lazy(() => import('./routes/About'))
  5. const App = () => (
  6. <Router>
  7. <Suspense fallback={LoadingComponent}>
  8. <Switch>
  9. <Route exact path="/" component={Home}/>
  10. <Route path="/about" component={About}/>
  11. </Switch>
  12. </Suspense>
  13. </Router>
  14. )

图片懒加载

Lazy Loading

  1. <img src = "product.jpg">
  2. //改为
  3. <img src = "placeholder.png" data-src="product.jpg">

window on scroll

  1. findImgs().each img
  2. new Image()
  3. .src = img.dataset.src
  4. .onload img.src = img.dataset.src

CSS代码优化

  1. 删除无用CSS
  2. 使用更高效的选择器
  3. 减少重排(reflow/relayout)
  4. 不要使用@import url.css
  5. 启用GPU硬件加速 transform:translate3d(0,0,0)
  6. 使用缩写(#FFFFFF→#FFF 0.1→.1 0px→0)
  7. 砍需求

JS代码优化

  1. 尽量不用全局变量
  2. 尽量少操作DOM
  3. 不要往页面中插入大量的HTML
  4. 尽量少触发重排
  5. 尽量少用闭包,避免内存泄漏(实际上是浏览器bug)
  6. 使用虚拟滚动列表(用库)

总结

工具:Network、Performance、Rendering、FPS、Coverage……
DNS:Prefetch
TCP:连接复用、并行化、HTTP管道、多路复用、服务器推
HTTP:合并、内联、压缩、精简、CookieFree、CDN
缓存、内容协商
CSS优化、JS优化
代码:位置、拆分、动态导入、懒加载、预加载

2021-8-11-16-35-21.pdf