
Web Performance Optimizasyonu Rehberi: Hızlı Web Siteleri Oluşturma
Web Performance Optimizasyonu Rehberi: Hızlı Web Siteleri Oluşturma
Web performansı, kullanıcı deneyimi ve SEO açısından kritik öneme sahiptir. Yavaş yüklenen siteler kullanıcıları kaybeder ve Google sıralamalarında geriye düşer. Bu rehberde, web sitenizin performansını artırmak için kullanabileceğiniz teknikleri öğreneceksiniz.
Web Performance Neden Önemli?
Kullanıcı Deneyimi
- 3 saniye kuralı: Kullanıcılar 3 saniyeden fazla beklemek istemez
- Bounce rate: Yavaş siteler yüksek bounce rate'e sahiptir
- Conversion rate: Hızlı siteler daha fazla satış yapar
SEO Etkisi
- Core Web Vitals: Google'ın sıralama faktörleri
- Mobile-first indexing: Mobil performans kritik
- Page Experience: Kullanıcı deneyimi sıralamayı etkiler
İş Etkisi
- Amazon: 100ms gecikme %1 satış kaybı
- Google: 500ms gecikme %20 trafik kaybı
- Walmart: 1 saniye hızlanma %2 conversion artışı
Core Web Vitals
1. Largest Contentful Paint (LCP)
LCP, sayfanın ana içeriğinin ne kadar hızlı yüklendiğini ölçer.
<!-- LCP optimizasyonu -->
<img src="hero-image.webp"
alt="Ana görsel"
loading="eager"
fetchpriority="high"
width="1200"
height="600">
<!-- Critical CSS inline -->
<style>
.hero-section {
background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
</style>
// LCP monitoring
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
if (entry.identifier === 'hero-image') {
console.log('LCP:', entry.startTime);
}
}
}).observe({ entryTypes: ['largest-contentful-paint'] });
2. First Input Delay (FID)
FID, kullanıcının ilk etkileşiminin ne kadar hızlı yanıt verdiğini ölçer.
// FID optimizasyonu
// Long tasks'ları böl
function processLargeData(data) {
// Büyük işlemi küçük parçalara böl
const chunkSize = 1000;
const chunks = [];
for (let i = 0; i < data.length; i += chunkSize) {
chunks.push(data.slice(i, i + chunkSize));
}
// Her chunk'ı ayrı task'ta işle
chunks.forEach((chunk, index) => {
setTimeout(() => {
processChunk(chunk);
}, index * 10);
});
}
// Web Workers kullan
const worker = new Worker('data-processor.js');
worker.postMessage({ data: largeDataset });
worker.onmessage = (event) => {
updateUI(event.data);
};
3. Cumulative Layout Shift (CLS)
CLS, sayfa yüklenirken layout'un ne kadar kararsız olduğunu ölçer.
<!-- CLS önleme -->
<img src="product-image.webp"
alt="Ürün görseli"
width="300"
height="400"
style="aspect-ratio: 3/4;">
<!-- Font loading optimizasyonu -->
<link rel="preload" href="fonts/custom-font.woff2" as="font" type="font/woff2" crossorigin>
<style>
@font-face {
font-family: 'CustomFont';
src: url('fonts/custom-font.woff2') format('woff2');
font-display: swap;
}
</style>
/* CLS önleme CSS teknikleri */
.reserved-space {
min-height: 400px;
aspect-ratio: 16/9;
}
.image-container {
position: relative;
width: 100%;
height: 0;
padding-bottom: 56.25%; /* 16:9 aspect ratio */
}
.image-container img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
Image Optimization
1. Modern Image Formats
<!-- WebP ve AVIF desteği -->
<picture>
<source srcset="image.avif" type="image/avif">
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="Optimized image">
</picture>
// Dynamic image optimization
function getOptimizedImageUrl(originalUrl, width, quality = 80) {
const url = new URL(originalUrl);
url.searchParams.set('w', width);
url.searchParams.set('q', quality);
url.searchParams.set('fm', 'webp');
return url.toString();
}
// Responsive images
const imageSizes = [320, 640, 960, 1280];
const srcset = imageSizes
.map(size => `${getOptimizedImageUrl('/image.jpg', size)} ${size}w`)
.join(', ');
2. Lazy Loading
<!-- Native lazy loading -->
<img src="image.jpg"
alt="Lazy loaded image"
loading="lazy"
width="300"
height="200">
<!-- Intersection Observer ile custom lazy loading -->
<div class="lazy-image" data-src="image.jpg"></div>
// Custom lazy loading
class LazyLoader {
constructor() {
this.images = document.querySelectorAll('[data-src]');
this.observer = new IntersectionObserver(this.handleIntersection.bind(this));
this.init();
}
init() {
this.images.forEach(img => this.observer.observe(img));
}
handleIntersection(entries) {
entries.forEach(entry => {
if (entry.isIntersecting) {
this.loadImage(entry.target);
this.observer.unobserve(entry.target);
}
});
}
loadImage(img) {
const src = img.dataset.src;
img.src = src;
img.classList.add('loaded');
}
}
new LazyLoader();
3. Image Compression
// Client-side image compression
async function compressImage(file, maxWidth = 1920, quality = 0.8) {
return new Promise((resolve) => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = () => {
// Aspect ratio koru
const ratio = Math.min(maxWidth / img.width, maxWidth / img.height);
canvas.width = img.width * ratio;
canvas.height = img.height * ratio;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
canvas.toBlob(resolve, 'image/webp', quality);
};
img.src = URL.createObjectURL(file);
});
}
// Kullanım
const fileInput = document.getElementById('image-upload');
fileInput.addEventListener('change', async (e) => {
const file = e.target.files[0];
const compressed = await compressImage(file);
// Compressed dosyayı upload et
uploadImage(compressed);
});
CSS ve JavaScript Optimizasyonu
1. Critical CSS
<!-- Critical CSS inline -->
<style>
/* Above-the-fold CSS */
.header { background: #fff; padding: 1rem; }
.hero { min-height: 100vh; display: flex; align-items: center; }
.cta-button { background: #007bff; color: white; padding: 1rem 2rem; }
</style>
<!-- Non-critical CSS async load -->
<link rel="preload" href="styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="styles.css"></noscript>
// Critical CSS extraction
function extractCriticalCSS() {
const criticalSelectors = [
'.header', '.hero', '.cta-button', '.navigation'
];
let criticalCSS = '';
// Stylesheet'leri analiz et
document.querySelectorAll('link[rel="stylesheet"]').forEach(link => {
// CSS'i parse et ve critical selector'ları bul
// Bu basit bir örnek, gerçek uygulamada daha karmaşık
});
return criticalCSS;
}
2. JavaScript Optimization
// Code splitting
import('./components/HeavyComponent.js').then(module => {
const HeavyComponent = module.default;
// Component'i render et
});
// Dynamic imports
const loadComponent = async (componentName) => {
const module = await import(`./components/${componentName}.js`);
return module.default;
};
// Bundle splitting
// webpack.config.js
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
common: {
name: 'common',
minChunks: 2,
chunks: 'all',
},
},
},
},
};
3. Tree Shaking
// ES6 modules ile tree shaking
import { debounce } from 'lodash-es'; // Sadece debounce import edilir
import { useState, useEffect } from 'react'; // Kullanılmayan import'lar çıkarılır
// Side-effect free modules
export const utils = {
add: (a, b) => a + b,
multiply: (a, b) => a * b,
};
// Conditional imports
const loadAnalytics = async () => {
if (process.env.NODE_ENV === 'production') {
const { default: analytics } = await import('./analytics.js');
return analytics;
}
return null;
};
Caching Strategies
1. Browser Caching
<!-- Cache headers -->
<meta http-equiv="Cache-Control" content="max-age=31536000, immutable">
<meta http-equiv="Expires" content="Wed, 21 Oct 2025 07:28:00 GMT">
// Service Worker ile caching
const CACHE_NAME = 'v1-cache';
const urlsToCache = [
'/',
'/styles.css',
'/app.js',
'/images/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 => {
// Cache'den döndür veya network'ten al
return response || fetch(event.request);
})
);
});
2. CDN Kullanımı
<!-- CDN kullanımı -->
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
// CDN fallback
function loadScript(src, fallback) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.onload = resolve;
script.onerror = () => {
if (fallback) {
loadScript(fallback).then(resolve).catch(reject);
} else {
reject(new Error(`Failed to load ${src}`));
}
};
document.head.appendChild(script);
});
}
// Kullanım
loadScript(
'https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js',
'/js/lodash.min.js'
).then(() => {
console.log('Lodash loaded');
});
Database ve API Optimizasyonu
1. Database Optimization
-- Index optimization
CREATE INDEX idx_user_email ON users(email);
CREATE INDEX idx_order_date ON orders(created_at);
-- Query optimization
SELECT u.name, o.total
FROM users u
INNER JOIN orders o ON u.id = o.user_id
WHERE u.created_at > '2024-01-01'
LIMIT 20;
-- Pagination
SELECT * FROM products
ORDER BY created_at DESC
LIMIT 20 OFFSET 40;
// Connection pooling
const pool = mysql.createPool({
host: 'localhost',
user: 'username',
password: 'password',
database: 'mydb',
connectionLimit: 10,
acquireTimeout: 60000,
timeout: 60000,
reconnect: true
});
// Prepared statements
const getUser = async (id) => {
const [rows] = await pool.execute(
'SELECT * FROM users WHERE id = ?',
[id]
);
return rows[0];
};
2. API Optimization
// GraphQL ile over-fetching önleme
const GET_USER = gql`
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
# Sadece ihtiyaç duyulan alanları iste
}
}
`;
// REST API pagination
const fetchUsers = async (page = 1, limit = 20) => {
const response = await fetch(
`/api/users?page=${page}&limit=${limit}`
);
return response.json();
};
// API response caching
const cache = new Map();
const cachedFetch = async (url, options = {}) => {
const cacheKey = `${url}-${JSON.stringify(options)}`;
if (cache.has(cacheKey)) {
const { data, timestamp } = cache.get(cacheKey);
if (Date.now() - timestamp < 5 * 60 * 1000) { // 5 dakika
return data;
}
}
const response = await fetch(url, options);
const data = await response.json();
cache.set(cacheKey, {
data,
timestamp: Date.now()
});
return data;
};
Monitoring ve Analytics
1. Performance Monitoring
// Web Vitals monitoring
import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals';
function sendToAnalytics(metric) {
const body = JSON.stringify(metric);
const url = '/analytics';
// Navigator.sendBeacon() kullan (page unload'da güvenilir)
if (navigator.sendBeacon) {
navigator.sendBeacon(url, body);
} else {
fetch(url, { body, method: 'POST', keepalive: true });
}
}
getCLS(sendToAnalytics);
getFID(sendToAnalytics);
getFCP(sendToAnalytics);
getLCP(sendToAnalytics);
getTTFB(sendToAnalytics);
2. Real User Monitoring (RUM)
// Custom performance monitoring
class PerformanceMonitor {
constructor() {
this.metrics = {};
this.init();
}
init() {
// Navigation timing
this.measureNavigationTiming();
// Resource timing
this.measureResourceTiming();
// User interactions
this.measureUserInteractions();
}
measureNavigationTiming() {
const navigation = performance.getEntriesByType('navigation')[0];
this.metrics.navigation = {
dns: navigation.domainLookupEnd - navigation.domainLookupStart,
tcp: navigation.connectEnd - navigation.connectStart,
ttfb: navigation.responseStart - navigation.requestStart,
domContentLoaded: navigation.domContentLoadedEventEnd - navigation.domContentLoadedEventStart,
load: navigation.loadEventEnd - navigation.loadEventStart
};
}
measureResourceTiming() {
const resources = performance.getEntriesByType('resource');
this.metrics.resources = resources.map(resource => ({
name: resource.name,
duration: resource.duration,
size: resource.transferSize,
type: resource.initiatorType
}));
}
measureUserInteractions() {
let firstInteraction = null;
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (!firstInteraction) {
firstInteraction = entry;
this.metrics.firstInteraction = entry.processingStart - entry.startTime;
}
}
});
observer.observe({ entryTypes: ['interaction'] });
}
sendMetrics() {
fetch('/api/metrics', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(this.metrics)
});
}
}
new PerformanceMonitor();
Performance Testing
1. Lighthouse CI
// lighthouse.config.js
module.exports = {
ci: {
collect: {
url: ['http://localhost:3000'],
numberOfRuns: 3,
},
assert: {
assertions: {
'categories:performance': ['warn', { minScore: 0.9 }],
'categories:accessibility': ['error', { minScore: 0.9 }],
'first-contentful-paint': ['warn', { maxNumericValue: 2000 }],
'largest-contentful-paint': ['error', { maxNumericValue: 2500 }],
'cumulative-layout-shift': ['error', { maxNumericValue: 0.1 }],
},
},
upload: {
target: 'temporary-public-storage',
},
},
};
2. WebPageTest
// WebPageTest API
const webPageTest = require('webpagetest');
const wpt = new webPageTest('www.webpagetest.org', 'YOUR_API_KEY');
wpt.runTest('https://example.com', {
location: 'Dulles:Chrome',
runs: 3,
firstViewOnly: false,
video: true,
timeline: true
}, (err, data) => {
if (err) {
console.error('Test failed:', err);
return;
}
console.log('Test ID:', data.testId);
console.log('Results URL:', data.data.summary);
});
Best Practices
1. Performance Budget
// Performance budget
const budget = {
javascript: {
size: '300kb',
time: '100ms'
},
css: {
size: '50kb',
time: '50ms'
},
images: {
size: '1mb',
count: 10
}
};
// Budget checking
function checkBudget(metrics) {
const violations = [];
if (metrics.javascript.size > parseSize(budget.javascript.size)) {
violations.push('JavaScript size exceeds budget');
}
if (metrics.css.size > parseSize(budget.css.size)) {
violations.push('CSS size exceeds budget');
}
return violations;
}
2. Progressive Enhancement
<!-- Progressive enhancement -->
<button class="cta-button" onclick="handleClick()">
Click me
</button>
<script>
// Enhanced functionality
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js');
}
if ('IntersectionObserver' in window) {
// Lazy loading
} else {
// Fallback
}
</script>
3. Critical Rendering Path
<!-- Critical rendering path optimization -->
<!DOCTYPE html>
<html>
<head>
<!-- Critical CSS inline -->
<style>
.header { background: #fff; }
.hero { min-height: 100vh; }
</style>
<!-- Preload critical resources -->
<link rel="preload" href="critical.js" as="script">
<link rel="preload" href="hero-image.webp" as="image">
<!-- Defer non-critical CSS -->
<link rel="preload" href="styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
</head>
<body>
<!-- Above-the-fold content -->
<header class="header">...</header>
<main class="hero">...</main>
<!-- Defer non-critical JavaScript -->
<script src="critical.js"></script>
<script>
// Load non-critical resources
window.addEventListener('load', () => {
const script = document.createElement('script');
script.src = 'non-critical.js';
document.body.appendChild(script);
});
</script>
</body>
</html>
Sonuç
Web performansı, modern web uygulamalarının başarısı için kritik öneme sahiptir. Bu rehberde öğrendiklerinizi pratik projelerde uygulayarak, hızlı ve kullanıcı dostu web siteleri oluşturabilirsiniz.
Önemli Noktalar:
- Core Web Vitals'ı takip edin
- Görselleri optimize edin
- CSS ve JavaScript'i minimize edin
- Caching stratejileri kullanın
- Performance monitoring yapın
Bu rehberde öğrendiklerinizi pratik projelerde uygulayarak, web performansı becerilerinizi geliştirebilirsiniz.
İlgili Kaynaklar: