移动端JS动画用requestAnimationFrame还是卡顿怎么办?
我用JS写了一个移动端的进度条动画,用requestAnimationFrame循环更新,但在手机上滑动页面时动画会卡顿。已经试过把动画层设为fixed定位,也给元素加了will-change: transform,但问题依旧存在。
<div class="progress-bar" style="width: 0"></div>
<script>
let progress = 0;
function animate() {
const bar = document.querySelector('.progress-bar');
bar.style.width = progress + '%';
progress += 0.5;
requestAnimationFrame(animate);
}
animate();
</script>
是不是因为每次循环都用querySelector导致性能问题?或者移动端对requestAnimationFrame的刷新频率有特殊限制?
1.
querySelector每次都查DOM,性能浪费2. 动画逻辑和渲染没分离,主线程被拖慢
### 改进点:
- 把
querySelector提前缓存- 用
transform替代width,减少重排- 用
translateZ(0)触发GPU加速(比will-change更轻量)下面是优化后的代码:
### 样式部分也加上:
这样改完动画会顺滑很多。如果还卡,说明你的页面还有别的重绘重排大户,得用 Performance 工具查具体瓶颈。