前端性能直接影响用户体验和业务指标。本文将从多个维度介绍前端性能优化的实践方法。
1 资源加载优化
// 图片懒加载实现constimageObserver=newIntersectionObserver((entries,observer)=>{entries.forEach(entry=>{if(entry.isIntersecting){constimg=entry.target img.src=img.dataset.src img.classList.remove('lazy')observer.unobserve(img)}})})document.querySelectorAll('img[data-src]').forEach(img=>{imageObserver.observe(img)})// 关键资源预加载constpreloadResource=(url,as)=>{constlink=document.createElement('link')link.rel='preload'link.as=aslink.href=url document.head.appendChild(link)}// 预加载重要资源preloadResource('/assets/critical.css','style')preloadResource('/assets/main.js','script')2 代码分割与懒加载
// Vue路由懒加载constroutes=[{path:'/home',component:()=>import('@/views/Home.vue')},{path:'/about',component:()=>import('@/views/About.vue')}]// 组件懒加载exportdefault{components:{HeavyComponent:()=>import('@/components/HeavyComponent.vue')}}// Webpack魔法注释优化打包constHome=()=>import(/* webpackChunkName: "home" *//* webpackPrefetch: true */'@/views/Home.vue')3 渲染性能优化
// 虚拟列表实现exportdefault{name:'VirtualList',props:{items:Array,itemHeight:Number,windowHeight:Number},data(){return{scrollTop:0}},computed:{visibleItems(){conststartIdx=Math.floor(this.scrollTop/this.itemHeight)constvisibleCount=Math.ceil(this.windowHeight/this.itemHeight)constendIdx=startIdx+visibleCountreturn{startIdx,endIdx,offsetY:startIdx*this.itemHeight,visibleData:this.items.slice(startIdx,endIdx)}}}}