为什么我的移动端动画 FPS 总是掉到 30 以下?
我在做一个移动端的滑动列表动画,用 requestAnimationFrame 写的,但实测 FPS 经常掉到 25~30,卡得不行。明明没做复杂计算,是不是哪里写错了?
试过用 Chrome DevTools 的 Performance 面板看,发现每一帧的样式计算和布局耗时特别高,但 DOM 结构也不复杂啊……
function animate() {
const el = document.getElementById('slider');
let start = null;
function step(timestamp) {
if (!start) start = timestamp;
const progress = timestamp - start;
el.style.transform = <code>translateX(${Math.min(progress / 2, 200)}px)</code>;
if (progress < 400) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
el.style.transform改成translate3d,开启硬件加速。再检查下有没有布局抖动,去掉所有影响布局的计算。记得用 will-change: transform 提前提示浏览器优化。累死我了,调试这种问题真折磨人。