Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / CSS

Desempenho da renderização nas DevTools: capturas, FPS, Paint flashing e Layers

As capturas mostram o aspeto da página, os FPS indicam a cadência, o Paint flashing realça as áreas pintadas e o Layers mostra as camadas de composição. Nenhum destes sinais é uma garantia de desempenho que se possa deduzir só do CSS.

Versão: Browser DevTools workflow; UI and feature availability vary by browser and version

Sintaxe

Performance, Screenshots, FPS, Paint flashing and Layers are DevTools diagnostics, not CSS syntax. Their names, availability and interfaces depend on the browser and its version; CSS specifications define the animation and media query used in the example, not the diagnostic tools. The example uses `animation: move-left 2s linear infinite alternate;` inside `@media (prefers-reduced-motion: no-preference)`. Replace `move-left` with `move-transform` in that declaration for the comparison.

Uma gravação em Performance fornece uma linha temporal onde podes procurar eventos de cálculo de estilos, disposição (layout) e pintura (paint). Quando disponível, Screenshots acrescenta uma sequência de capturas feitas em instantes selecionados. Relaciona-as com os eventos da gravação: não registam todos os fotogramas nem medem o custo da renderização.

FPS significa fotogramas por segundo. Analisa também os tempos de cada fotograma: uma boa média pode ocultar solavancos pontuais. A 60 Hz, passam cerca de 16,7 ms entre atualizações do ecrã; não é um orçamento de tempo universal. Paint flashing realça as zonas que estão a ser pintadas ou repintadas, mas não mede quanto tempo isso demora. Mesmo sem realces, o compositor pode estar a combinar conteúdo já pintado.

Layers mostra as camadas usadas pelo compositor, não as camadas da cascata CSS (@layer) nem os contextos de empilhamento. Um transform diferente de none cria um contexto de empilhamento numa caixa CSS normal, mas não garante uma camada de composição separada. will-change é uma indicação para otimização, não uma ordem para criar uma camada; camadas adicionais podem consumir memória.

Compara o mesmo movimento com left e transform. Alterar left pode exigir layout e pintura, enquanto animar transform pode ser tratado só na composição. São hipóteses a testar, não garantias do CSS. Repete as medições nas mesmas condições e verifica os resultados nos dispositivos a que a página se destina. Os nomes e a disponibilidade das ferramentas dependem do navegador e da respetiva versão.

Exemplos

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Rendering performance comparison</title>
  <style>
    #square {
      position: relative;
      left: 0;
      width: 48px;
      height: 48px;
      background: #2563eb;
    }

    @media (prefers-reduced-motion: no-preference) {
      #square {
        animation: move-left 2s linear infinite alternate;
      }
    }

    @keyframes move-left {
      from { left: 0; }
      to   { left: 120px; }
    }

    @keyframes move-transform {
      from { transform: translateX(0); }
      to   { transform: translateX(120px); }
    }
  </style>
</head>
<body>
  <div id="track"><div id="square"></div></div>
  <p><output id="observation"></output></p>
  <script>
    const track = document.querySelector('#track');
    const square = document.querySelector('#square');
    const observation = document.querySelector('#observation');
    const motion = matchMedia('(prefers-reduced-motion: no-preference)');
    const variants = ['move-left', 'move-transform'];
    const origin = track.getBoundingClientRect();
    const { width, height } = square.getBoundingClientRect();
    const { animationName, backgroundColor } = getComputedStyle(square);
    const close = (a, b) => Math.abs(a - b) < 0.01;

    function check(condition, message) {
      if (!condition) throw new Error(message);
    }

    // Sample the actual CSS animation at known times, before profiling it.
    function measure(name) {
      square.style.animationName = name;
      const [animation] = square.getAnimations();
      check(animation?.animationName === name, `Missing animation: ${name}`);
      animation.pause();

      const { duration, direction, iterations } = animation.effect.getTiming();
      check(duration === 2000 && direction === 'alternate' && iterations === Infinity,
        `Unexpected timing: ${name}`);

      const offsets = [0, 0.5, 1, 1.5, 2].map(step => {
        animation.currentTime = step * duration;
        const rect = square.getBoundingClientRect();
        check(close(rect.top, origin.top), `Unexpected vertical movement: ${name}`);
        return rect.left - origin.left;
      });
      check(offsets.every((x, i) => close(x, [0, 60, 120, 60, 0][i])),
        `Unexpected horizontal movement: ${name}`);
      return { distance: Math.round(offsets[2] - offsets[0]), seconds: duration / 1000 };
    }

    try {
      check(width === 48 && height === 48 && backgroundColor === 'rgb(37, 99, 235)',
        'Unexpected square size or color');

      if (motion.matches) {
        check(variants.includes(animationName), 'The media query did not activate a comparison variant');
        let measured;
        try {
          measured = measure(animationName);
          measure(variants.find(name => name !== animationName));
        } finally {
          // Remove the paused test animation and let the stylesheet start a fresh one.
          square.style.animationName = 'none';
          square.getAnimations();
          square.style.removeProperty('animation-name');
        }
        const { distance, seconds } = measured;
        observation.textContent = `When the media query matches, a blue ${width} × ${height} CSS-pixel square moves ${distance} CSS pixels to the right in ${seconds} seconds and back in ${seconds} seconds, repeating in either variant. Otherwise it stays at the starting position. No specific FPS, paint pattern, timing cost or layer configuration is expected across browsers and devices.`;
      } else {
        const rect = square.getBoundingClientRect();
        check(animationName === 'none' && square.getAnimations().length === 0 &&
          close(rect.left, origin.left) && close(rect.top, origin.top),
          'The square is not static at its starting position');
        observation.textContent = `The media query does not match. The blue ${width} × ${height} CSS-pixel square stays at the starting position.`;
      }
    } catch (error) {
      observation.textContent = error.message;
      throw error;
    }
  </script>
</body>
</html>

Resultado

When the media query matches, a blue 48 × 48 CSS-pixel square moves 120 CSS pixels to the right in 2 seconds and back in 2 seconds, repeating in either variant. Otherwise it stays at the starting position. No specific FPS, paint pattern, timing cost or layer configuration is expected across browsers and devices.

Altera apenas o nome da animação de `move-left` para `move-transform`. Verifica se o quadrado percorre a mesma distância no mesmo tempo e depois compara as gravações. Se `prefers-reduced-motion: no-preference` não corresponder, o quadrado fica imóvel.

Lições relacionadas

  • CSS · Lição 29 · Avançado · Versão: 2

Fontes