代码位置优化
1.不阻塞html解析,尽早下载
2.防止被外部JS阻塞
…
1.可直接访问DOM,无需监听DOM Ready
2.避免阻塞html解析
代码拆分
main.aaa.js → main.bbb.js
1MB更改会重新下载
JS
- runtime-xxx.js
- rendor-xxx.js
- common-xxx.js
- page-index-xxx.js
CSS
- reset.normolize.css
- rendor-xxx.css
- common-xxx.css
- page-admin-xxx.css
JS动态导入
const array=[1,2,3]
import('lodash').then( _ =>{
const clone = _.cloneDeep(array)
})
Vue动态导入
const router = new VueRouter({
routes:[
{path:'/home',component:()=>import('./Home.vue')},
{path:'/about',component:()=>({
component:import('./About.vue'),
loading:LoadingComponent,
error:ErrorComponent,
})}
]
})
React动态导入
import React, { Suspense, lazy } from 'react'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
const Home = lazy(() => import('./routes/Home'))
const About = lazy(() => import('./routes/About'))
const App = () => (
<Router>
<Suspense fallback={LoadingComponent}>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
</Switch>
</Suspense>
</Router>
)
图片懒加载
Lazy Loading
<img src = "product.jpg">
//改为
<img src = "placeholder.png" data-src="product.jpg">
window on scroll
findImgs().each img
new Image()
.src = img.dataset.src
.onload img.src = img.dataset.src
CSS代码优化
- 删除无用CSS
- 使用更高效的选择器
- 减少重排(reflow/relayout)
- 不要使用@import url.css
- 启用GPU硬件加速
transform:translate3d(0,0,0)
- 使用缩写(#FFFFFF→#FFF 0.1→.1 0px→0)
- 砍需求
JS代码优化
- 尽量不用全局变量
- 尽量少操作DOM
- 不要往页面中插入大量的HTML
- 尽量少触发重排
- 尽量少用闭包,避免内存泄漏(实际上是浏览器bug)
- 使用虚拟滚动列表(用库)
总结
工具:Network、Performance、Rendering、FPS、Coverage……
DNS:Prefetch
TCP:连接复用、并行化、HTTP管道、多路复用、服务器推
HTTP:合并、内联、压缩、精简、CookieFree、CDN
缓存、内容协商
CSS优化、JS优化
代码:位置、拆分、动态导入、懒加载、预加载