Programação

Performance Web: Otimize Seu Site para Carregar em 1 Segundo

Guia completo de otimização web: Core Web Vitals, lazy loading, compressão, cache, CDN e técnicas para sites ultra-rápidos.

Performance Web: Guia Completo de Otimização 2025

Performance web não é luxo - é necessidade. Sites lentos perdem usuários, conversões e ranqueamento no Google. Vamos aprender a otimizar cada aspecto do seu site.

Por Que Performance Importa?

Impacto nos Negócios

  • 53% dos usuários abandonam sites que demoram +3s
  • 1 segundo de atraso = 7% menos conversões
  • 100ms mais rápido = 1% mais conversões (Amazon)
  • Sites rápidos ranqueiam melhor no Google

Core Web Vitals (Google)

LCP (Largest Contentful Paint)

  • Tempo até maior elemento visível carregar
  • ✅ Bom: < 2.5s
  • ⚠️ Precisa melhorar: 2.5-4s
  • ❌ Ruim: > 4s

FID (First Input Delay)

  • Tempo até primeira interação responder
  • ✅ Bom: < 100ms
  • ⚠️ Precisa melhorar: 100-300ms
  • ❌ Ruim: > 300ms

CLS (Cumulative Layout Shift)

  • Estabilidade visual (elementos não devem "pular")
  • ✅ Bom: < 0.1
  • ⚠️ Precisa melhorar: 0.1-0.25
  • ❌ Ruim: > 0.25

1. Otimização de Imagens

Formatos Modernos

<!-- WebP com fallback -->
<picture>
  <source srcset="image.webp" type="image/webp">
  <source srcset="image.jpg" type="image/jpeg">
  <img src="image.jpg" alt="Descrição">
</picture>

<!-- AVIF (ainda mais eficiente) -->
<picture>
  <source srcset="image.avif" type="image/avif">
  <source srcset="image.webp" type="image/webp">
  <img src="image.jpg" alt="Descrição">
</picture>

Lazy Loading

<!-- Nativo -->
<img src="image.jpg" loading="lazy" alt="Descrição">

<!-- Priorizar imagens above-the-fold -->
<img src="hero.jpg" loading="eager" alt="Hero">
<img src="below.jpg" loading="lazy" alt="Abaixo da dobra">

Responsive Images

<!-- Diferentes tamanhos para diferentes telas -->
<img
  srcset="
    small.jpg 400w,
    medium.jpg 800w,
    large.jpg 1200w
  "
  sizes="
    (max-width: 400px) 400px,
    (max-width: 800px) 800px,
    1200px
  "
  src="medium.jpg"
  alt="Imagem responsiva"
>

Compressão

# ImageMagick
convert input.jpg -quality 85 output.jpg

# Sharp (Node.js)
npm install sharp
const sharp = require('sharp');

sharp('input.jpg')
  .resize(800)
  .webp({ quality: 80 })
  .toFile('output.webp');

Dimensões Explícitas (Evitar CLS)

<!-- ❌ Sem dimensões (causa CLS) -->
<img src="image.jpg" alt="Imagem">

<!-- ✅ Com dimensões -->
<img src="image.jpg" width="800" height="600" alt="Imagem">

<!-- ✅ Com aspect-ratio CSS -->
<img src="image.jpg" alt="Imagem" style="aspect-ratio: 16/9;">

2. Otimização de JavaScript

Code Splitting

// ❌ Importar tudo
import { heavyLibrary } from 'heavy-library';

// ✅ Importação dinâmica
const loadHeavyFeature = async () => {
  const { heavyLibrary } = await import('heavy-library');
  return heavyLibrary();
};

// React lazy loading
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));

function App() {
  return (
    <Suspense fallback={<Loading />}>
      <HeavyComponent />
    </Suspense>
  );
}

Tree Shaking

// ❌ Importar biblioteca inteira
import _ from 'lodash';
_.debounce(fn, 300);

// ✅ Importar apenas o necessário
import debounce from 'lodash/debounce';
debounce(fn, 300);

// ✅ Ainda melhor: usar nativo quando possível
const debounce = (fn, delay) => {
  let timeout;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn(...args), delay);
  };
};

Minificação e Compressão

// webpack.config.js
const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
  optimization: {
    minimize: true,
    minimizer: [new TerserPlugin({
      terserOptions: {
        compress: {
          drop_console: true, // Remove console.logs
        },
      },
    })],
  },
};

Defer e Async

<!-- ❌ Bloqueia renderização -->
<script src="script.js"></script>

<!-- ✅ Async (não bloqueia, executa quando pronto) -->
<script src="analytics.js" async></script>

<!-- ✅ Defer (não bloqueia, executa após HTML) -->
<script src="app.js" defer></script>

<!-- Ordem de execução -->
<!-- defer: mantém ordem, executa após DOM -->
<!-- async: não mantém ordem, executa ASAP -->

3. Otimização de CSS

Critical CSS

<!-- Inline CSS crítico no <head> -->
<style>
  /* CSS necessário para above-the-fold */
  body { margin: 0; font-family: sans-serif; }
  .hero { height: 100vh; background: #000; }
</style>

<!-- Carregar resto do CSS de forma assíncrona -->
<link rel="preload" href="styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="styles.css"></noscript>

Remover CSS Não Utilizado

# PurgeCSS
npm install -D @fullhuman/postcss-purgecss

# postcss.config.js
module.exports = {
  plugins: [
    require('@fullhuman/postcss-purgecss')({
      content: ['./src/**/*.html', './src/**/*.js'],
    }),
  ],
};

CSS Moderno

/* ❌ Muitas propriedades */
.box {
  margin-top: 10px;
  margin-right: 20px;
  margin-bottom: 10px;
  margin-left: 20px;
}

/* ✅ Shorthand */
.box {
  margin: 10px 20px;
}

/* Use CSS Grid/Flexbox em vez de floats */
.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

4. Otimização de Fontes

Font Display

@font-face {
  font-family: 'CustomFont';
  src: url('font.woff2') format('woff2');
  font-display: swap; /* Mostra fallback até carregar */
}

/* Opções:
   - auto: padrão do navegador
   - block: invisível até carregar (FOIT)
   - swap: mostra fallback imediatamente (FOUT)
   - fallback: híbrido
   - optional: usa fallback se não carregar rápido
*/

Preload Fontes Críticas

<link rel="preload" href="font.woff2" as="font" type="font/woff2" crossorigin>

Subset de Fontes

/* Carregar apenas caracteres necessários */
@font-face {
  font-family: 'CustomFont';
  src: url('font-latin.woff2') format('woff2');
  unicode-range: U+0000-00FF; /* Apenas Latin */
}

Fontes Variáveis

/* Uma fonte com múltiplos pesos */
@font-face {
  font-family: 'Inter';
  src: url('inter-variable.woff2') format('woff2-variations');
  font-weight: 100 900; /* Todos os pesos */
}

.text {
  font-weight: 450; /* Qualquer valor entre 100-900 */
}

5. Caching e CDN

Cache Headers

# nginx.conf
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
  expires 1y;
  add_header Cache-Control "public, immutable";
}

location ~* \.(html)$ {
  expires 1h;
  add_header Cache-Control "public, must-revalidate";
}

Service Worker

// sw.js
const CACHE_NAME = 'v1';
const urlsToCache = [
  '/',
  '/styles.css',
  '/script.js',
  '/logo.png'
];

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then((cache) => cache.addAll(urlsToCache))
  );
});

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request)
      .then((response) => response || fetch(event.request))
  );
});

CDN

<!-- Usar CDN para bibliotecas -->
<script src="https://cdn.jsdelivr.net/npm/react@18/umd/react.production.min.js"></script>

<!-- Seus assets em CDN -->
<img src="https://cdn.seusite.com/images/hero.jpg" alt="Hero">

6. Resource Hints

Preconnect

<!-- Conectar antecipadamente a domínios externos -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://cdn.example.com">

DNS Prefetch

<!-- Resolver DNS antecipadamente -->
<link rel="dns-prefetch" href="https://analytics.google.com">

Preload

<!-- Carregar recursos críticos antecipadamente -->
<link rel="preload" href="hero.jpg" as="image">
<link rel="preload" href="font.woff2" as="font" crossorigin>
<link rel="preload" href="critical.css" as="style">

Prefetch

<!-- Carregar recursos para próxima navegação -->
<link rel="prefetch" href="/next-page.html">
<link rel="prefetch" href="secondary-image.jpg">

7. Otimização de Renderização

Evitar Layout Thrashing

// ❌ Ruim (força reflow múltiplas vezes)
elements.forEach(el => {
  const height = el.offsetHeight; // Read
  el.style.height = height + 10 + 'px'; // Write
});

// ✅ Bom (batch reads e writes)
const heights = elements.map(el => el.offsetHeight); // Read all
elements.forEach((el, i) => {
  el.style.height = heights[i] + 10 + 'px'; // Write all
});

RequestAnimationFrame

// ❌ Ruim
setInterval(() => {
  element.style.left = position + 'px';
  position += 1;
}, 16);

// ✅ Bom
function animate() {
  element.style.left = position + 'px';
  position += 1;
  requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

CSS Containment

/* Isolar mudanças de layout */
.card {
  contain: layout style paint;
}

/* Ou específico */
.sidebar {
  contain: layout; /* Mudanças não afetam fora */
}

Will-Change

/* Avisar navegador sobre animações */
.animated {
  will-change: transform, opacity;
}

/* Remover após animação */
.animated.done {
  will-change: auto;
}

8. Otimização de Rede

HTTP/2

# nginx.conf
listen 443 ssl http2;

Benefícios:

  • Multiplexing (múltiplas requisições em uma conexão)
  • Server Push
  • Compressão de headers

Compressão Gzip/Brotli

# nginx.conf
gzip on;
gzip_types text/plain text/css application/json application/javascript;
gzip_min_length 1000;

# Brotli (melhor que gzip)
brotli on;
brotli_types text/plain text/css application/json application/javascript;

Reduzir Requisições

// ❌ Múltiplas requisições
fetch('/api/user');
fetch('/api/posts');
fetch('/api/comments');

// ✅ Uma requisição
fetch('/api/dashboard'); // Retorna tudo junto

9. Monitoramento

Lighthouse

# CLI
npm install -g lighthouse
lighthouse https://seusite.com --view

# Programático
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');

(async () => {
  const chrome = await chromeLauncher.launch();
  const result = await lighthouse('https://seusite.com', {
    port: chrome.port
  });
  console.log(result.lhr.categories.performance.score * 100);
  await chrome.kill();
})();

Web Vitals

import {getCLS, getFID, getFCP, getLCP, getTTFB} from 'web-vitals';

function sendToAnalytics(metric) {
  console.log(metric);
  // Enviar para seu analytics
}

getCLS(sendToAnalytics);
getFID(sendToAnalytics);
getFCP(sendToAnalytics);
getLCP(sendToAnalytics);
getTTFB(sendToAnalytics);

Performance API

// Medir tempo de carregamento
window.addEventListener('load', () => {
  const perfData = performance.getEntriesByType('navigation')[0];
  console.log('DOM Content Loaded:', perfData.domContentLoadedEventEnd);
  console.log('Load Complete:', perfData.loadEventEnd);
});

// Medir operações específicas
performance.mark('start-operation');
// ... operação ...
performance.mark('end-operation');
performance.measure('operation', 'start-operation', 'end-operation');

const measure = performance.getEntriesByName('operation')[0];
console.log('Duração:', measure.duration);

10. Checklist de Performance

### Imagens
✅ Formato WebP/AVIF
✅ Lazy loading
✅ Responsive images
✅ Dimensões explícitas
✅ Compressão adequada

### JavaScript
✅ Code splitting
✅ Tree shaking
✅ Minificação
✅ Defer/Async
✅ Remover código não usado

### CSS
✅ Critical CSS inline
✅ Remover CSS não usado
✅ Minificação
✅ Evitar @import

### Fontes
✅ font-display: swap
✅ Preload fontes críticas
✅ WOFF2 format
✅ Subset quando possível

### Caching
✅ Cache headers configurados
✅ Service Worker
✅ CDN configurado

### Rede
✅ HTTP/2 ativado
✅ Gzip/Brotli ativado
✅ Reduzir requisições
✅ Resource hints

### Core Web Vitals
✅ LCP < 2.5s
✅ FID < 100ms
✅ CLS < 0.1

Ferramentas Essenciais

Análise

  • Lighthouse - Auditoria completa
  • WebPageTest - Teste detalhado
  • Chrome DevTools - Performance profiling
  • GTmetrix - Análise e recomendações

Otimização

  • ImageOptim - Compressão de imagens
  • Squoosh - Converter para WebP/AVIF
  • PurgeCSS - Remover CSS não usado
  • Webpack Bundle Analyzer - Analisar bundle

Monitoramento

  • Google Analytics - Web Vitals
  • New Relic - APM
  • Datadog - Monitoramento real-time

Conclusão

Performance web é um processo contínuo. Meça, otimize, monitore e repita. Cada milissegundo conta para experiência do usuário e sucesso do negócio.

Principais Pontos:

  • ⚡ Otimize imagens (maior impacto)
  • 📦 Code splitting e lazy loading
  • 🎯 Foque em Core Web Vitals
  • 📊 Monitore constantemente
  • 🔄 Melhoria contínua

---

Precisa de auditoria de performance? A HG Soluções pode analisar e otimizar seu site para máxima velocidade.

Entre em contato: [https://hgsolucoes.com](https://hgsolucoes.com)