首页 > 解决方案 > 动态 CSS 内容性能

问题描述

我有一个 requestAnimationFrame 循环,我需要将 innerText 设置为使用 javascript 测量的 fps。我想知道是否有更有效的方法来做到这一点(因为我认为设置 innerText 会导致每帧重排/重绘)?仅对于 fps,这可能不会导致任何性能损失,但由于我想使用这种机制添加/更改更多元素,我想知道是否有更有效的方法来做到这一点?

我尝试更改 css 变量:#fps-counter:before { content: var(--css-fps-var) }并在循环中更改 --css-fps-var ,但这没有用。现在我解决了一个我使用数据属性更新的数据属性:#fps-counter:before { content: attr(data-fps); }

我不知道这是否会更好,我认为它应该但我不确定..有没有更好的方法来做到这一点?

编辑1:

不幸的是我不能使用画布,我必须使用 DOM 元素来实现这一点..

标签: javascriptcssperformancecustom-data-attributecss-variables

解决方案


在 a 中将值绘制为文本<canvas>不会触发 DOM 的任何布局/重排:

const times = [];
let fps;
const canvas = document.getElementById('fpsCounter');
const ctx = canvas.getContext('2d');
ctx.font = '16px sans-serif';

function refreshLoop() {
  window.requestAnimationFrame(() => {
    const now = performance.now();
    while (times.length > 0 && times[0] <= now - 1000) {
      times.shift();
    }
    times.push(now);
    fps = times.length;
    ctx.fillStyle = '#000000';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = '#FFFFFF';
    ctx.fillText(`fps: ${fps}`, 10, 16);
    refreshLoop();
  });
}

refreshLoop();
<canvas id="fpsCounter" width="100" height="20" style="position: absolute; top: 10px; left: 10px;"/>


推荐阅读