前端性能优化方式
1、实现数据懒加载:
方法一:使用原生自带的IntersectionObserver对象通过获取dom节点实现数据懒加载
<div class="bottom" ref="bottom">测试的视图窗口区</div>
const bottom = ref(null)
onMounted(() => {
const intersectionObserver = new IntersectionObserver((entries) => {
if (entries[0].intersectionRatio <= 0) {
return console.warn('视图不可见==')
}
console.warn('视图可见===')
})
intersectionObserver.observe(bottom.value)
})
方法二:使用vueuse中提供的useIntersectionObserver 可实现数据的懒加载效果
import { useIntersectionObserver } from '@vueuse/core'
const bottom = ref(null)
onMounted(() => {
const { stop } = useIntersectionObserver(bottom, ([{ isIntersecting }]) => {
if (isIntersecting) {
console.warn('视图可见===')
// 渲染完成后停止监听
stop()
} else {
console.warn('视图不可见==')
}
})
})
2、实现图片的懒加载:
通过自定义指令的方式实现图片懒加载,在src/directive/index.js中实现懒加载的相关逻辑
// directive/index.js
import { useIntersectionObserver } from '@vueuse/core'
const imgLazy = {
mounted(el) {
const preSrc = el.src
// 占位图-预加载图片
el.src = 'https://res.lgdsunday.club/img-load.png'
const { stop } = new useIntersectionObserver(el, ([{ isIntersecting }]) => {
if (isIntersecting) {
el.src = preSrc
stop()
}
})
}
}
export default {
install: (app) => {
app.directive('imgLazy', imgLazy)
}
}
在main.js中引入
import directive from './directive'
app.use(directive)
在img标签中可以通过v-imgLazy进行使用实现图片懒加载的过程
3、减少Http的请求:
- 将多个CSS文件和JavaScript文件合并为一个文件,减少Http的请求次数
- 将多个图片合并为一张大图,使用定位的方式进行显示
4、压缩文件使资源最小化
- 将css和JavaScript文件、图片进行压缩,减少文件和图片的大小
- 删除未使用或冗余的代码逻辑
5、优化CSS和JavaScript
- 减少css重排和重绘
- 使用css动画替代JavaScript动画
6、使用缓存
- 利用浏览器缓存机制设置适合的缓存头
- 使用keep-alive缓存不常用的组件
7、使用CDN
- 将静态资源部署到CDN上,减少网络延迟(将资源放在遍布世界各地的服务器上,访问资源时,请求会重定向到离用户最近的服务节点上)
8、实现路由懒加载
- 通过import()实现路由的异步加载