Performance Web: Como otimizar seu site para carregar em menos de 3 segundos
A velocidade de carregamento é crucial para o sucesso do seu site. Usuários abandonam páginas que demoram mais de 3 segundos para carregar. Vamos ver como otimizar isso.
1. Otimização de Imagens
As imagens são frequentemente o maior gargalo de performance:
Formatos modernos
<picture>
<source srcset="image.avif" type="image/avif">
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="Descrição" loading="lazy">
</picture>
Responsive images
<img
srcset="small.jpg 480w, medium.jpg 800w, large.jpg 1200w"
sizes="(max-width: 480px) 100vw, (max-width: 800px) 50vw, 25vw"
src="medium.jpg"
alt="Imagem responsiva"
>
2. Code Splitting e Lazy Loading
Carregue apenas o código necessário:
// Dynamic imports
const HeavyComponent = lazy(() => import('./HeavyComponent'));
function App() {
return (
<Suspense fallback={<Loading />}>
<HeavyComponent />
</Suspense>
);
}
Route-based splitting
// Em Next.js
const DashboardPage = dynamic(() => import('../pages/dashboard'), {
loading: () => <p>Carregando...</p>,
});
3. Otimização de CSS
Critical CSS
<style>
/* CSS crítico inline */
.header { background: #fff; height: 60px; }
.hero { min-height: 400px; }
</style>
<link rel="preload" href="/styles/main.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
CSS purging
// Em Tailwind CSS
module.exports = {
content: ['./src/**/*.{js,jsx,ts,tsx}'],
// Remove CSS não utilizado
}
4. Otimização de JavaScript
Tree shaking
// ❌ Importa toda a biblioteca
import * as _ from 'lodash';
// ✅ Importa apenas o necessário
import debounce from 'lodash/debounce';
Bundle analysis
# Analise o tamanho do bundle
npm install --save-dev webpack-bundle-analyzer
npx webpack-bundle-analyzer build/static/js/*.js
5. Caching Estratégico
Service Workers
// sw.js
const CACHE_NAME = 'v1';
const urlsToCache = [
'/',
'/static/css/main.css',
'/static/js/main.js'
];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.addAll(urlsToCache))
);
});
HTTP Headers
# nginx.conf
location ~* \.(js|css|png|jpg|jpeg|gif|svg|woff2)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
6. Otimização de Fontes
Font loading strategy
@font-face {
font-family: 'CustomFont';
src: url('font.woff2') format('woff2');
font-display: swap; /* Mostra fallback enquanto carrega */
}
Preload critical fonts
<link rel="preload" href="/fonts/main.woff2" as="font" type="font/woff2" crossorigin>
7. Database e API Optimization
Pagination
// API com paginação
app.get('/api/posts', (req, res) => {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const offset = (page - 1) * limit;
const posts = Posts.findAll({
limit,
offset,
order: [['createdAt', 'DESC']]
});
res.json({ posts, page, hasMore: posts.length === limit });
});
Data fetching
// React Query para caching
function PostList() {
const { data, isLoading } = useQuery(
['posts', page],
() => fetchPosts(page),
{
staleTime: 5 * 60 * 1000, // 5 minutos
cacheTime: 10 * 60 * 1000 // 10 minutos
}
);
if (isLoading) return <Skeleton />;
return (
<div>
{data.posts.map(post => (
<PostCard key={post.id} post={post} />
))}
</div>
);
}
8. Métricas e Monitoramento
Core Web Vitals
// Medindo performance
function measureWebVitals() {
getCLS(console.log); // Cumulative Layout Shift
getFID(console.log); // First Input Delay
getLCP(console.log); // Largest Contentful Paint
}
Lighthouse CI
# .github/workflows/lighthouse.yml
name: Lighthouse
on: [push]
jobs:
lighthouse:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Audit URLs using Lighthouse
uses: treosh/lighthouse-ci-action@v7
with:
urls: |
https://your-site.com
https://your-site.com/blog
9. Otimização de CDN
Next.js Image Optimization
import Image from 'next/image';
function OptimizedImage() {
return (
<Image
src="/hero.jpg"
alt="Hero image"
width={1200}
height={600}
priority // Para imagens above the fold
placeholder="blur"
blurDataURL="data:image/jpeg;base64,..."
/>
);
}
10. Checklist de Performance
- Imagens otimizadas (WebP/AVIF)
- Code splitting implementado
- CSS crítico inline
- Fonts com font-display: swap
- Service Worker configurado
- Lazy loading para conteúdo below-the-fold
- Bundle size < 250KB
- First Contentful Paint < 1.8s
- Largest Contentful Paint < 2.5s
- Cumulative Layout Shift < 0.1
Conclusão
Performance web não é um luxo, é uma necessidade. Implemente essas técnicas gradualmente e monitore os resultados. Lembre-se: cada milissegundo conta para a experiência do usuário e para o SEO.

Comentários
0 ComentáriosSeja o primeiro a comentar neste artigo.