Performance
12/18/2023
15 min read
Complete Guide to Web Performance Optimization
Comprehensive strategies to improve your website's loading speed and user experience.
Published by Lipsum Technologies
Web performance directly impacts user experience, search rankings, and business metrics. A one-second delay in page load time can result in a 7% reduction in conversions. This comprehensive guide covers all aspects of web performance optimization.
Understanding Web Performance Metrics
Core Web Vitals
- Largest Contentful Paint (LCP): Loading performance (should be ≤ 2.5s)
- First Input Delay (FID): Interactivity (should be ≤ 100ms)
- Cumulative Layout Shift (CLS): Visual stability (should be ≤ 0.1)
Additional Important Metrics
- First Contentful Paint (FCP): When first content appears
- Time to Interactive (TTI): When page becomes fully interactive
- Total Blocking Time (TBT): Time when main thread is blocked
- Speed Index: How quickly content is visually displayed
Frontend Optimization Strategies
HTML Optimization
- Minimize DOM depth and complexity
- Use semantic HTML for better parsing
- Eliminate unnecessary whitespace and comments
- Optimize critical rendering path
CSS Optimization
/* Critical CSS inlining */
<style>
/* Above-the-fold styles */
.header { /* critical styles */ }
</style>
/* Non-critical CSS loading */
<link rel="preload" href="styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
JavaScript Optimization
- Code splitting and lazy loading
- Tree shaking to remove unused code
- Minification and compression
- Async and defer script loading
Image Optimization
Format Selection
- WebP: 25-35% smaller than JPEG
- AVIF: 50% smaller than JPEG (newer format)
- JPEG: Best for photographs
- PNG: Best for graphics with transparency
- SVG: Best for simple graphics and icons
Responsive Images
<picture>
<source srcset="image.avif" type="image/avif">
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="Description"
srcset="image-320w.jpg 320w,
image-640w.jpg 640w,
image-1280w.jpg 1280w"
sizes="(max-width: 320px) 280px,
(max-width: 640px) 600px,
1200px">
</picture>
Lazy Loading
/* Native lazy loading */
<img src="image.jpg" loading="lazy" alt="Description">
/* Intersection Observer for custom lazy loading */
const imageObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.classList.remove('lazy');
imageObserver.unobserve(img);
}
});
});
Network Optimization
HTTP/2 and HTTP/3
- Multiplexing eliminates head-of-line blocking
- Server push for critical resources
- Header compression reduces overhead
- Binary protocol for efficiency
Resource Hints
<!-- DNS prefetch for external domains -->
<link rel="dns-prefetch" href="//fonts.googleapis.com">
<!-- Preconnect for critical third-party origins -->
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<!-- Preload critical resources -->
<link rel="preload" href="critical.css" as="style">
<link rel="preload" href="hero-image.jpg" as="image">
<!-- Prefetch for likely next navigation -->
<link rel="prefetch" href="/next-page.html">
Caching Strategies
Browser Caching
# Apache .htaccess
<IfModule mod_expires.c>
ExpiresActive on
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
</IfModule>
Service Worker Caching
// Cache-first strategy for static assets
self.addEventListener('fetch', event => {
if (event.request.destination === 'image') {
event.respondWith(
caches.match(event.request).then(response => {
return response || fetch(event.request).then(fetchResponse => {
const responseClone = fetchResponse.clone();
caches.open('images-v1').then(cache => {
cache.put(event.request, responseClone);
});
return fetchResponse;
});
})
);
}
});
Server-Side Optimization
Compression
- Gzip compression (reduces size by 70-90%)
- Brotli compression (10-15% better than Gzip)
- Dynamic compression for HTML/CSS/JS
- Pre-compression for static assets
Server Response Optimization
- Minimize Time to First Byte (TTFB)
- Use CDN for global content delivery
- Implement database query optimization
- Use server-side caching (Redis, Memcached)
Third-Party Script Optimization
Loading Strategies
<!-- Async loading for non-critical scripts -->
<script async src="analytics.js"></script>
<!-- Defer for scripts that need DOM -->
<script defer src="interactive.js"></script>
<!-- Dynamic loading for conditional scripts -->
<script>
if (condition) {
const script = document.createElement('script');
script.src = 'conditional.js';
document.head.appendChild(script);
}
</script>
Third-Party Monitoring
- Audit third-party impact regularly
- Use resource hints for external domains
- Implement timeout mechanisms
- Consider self-hosting critical third-party assets
Performance Monitoring
Real User Monitoring (RUM)
// Web Vitals measurement
import {getCLS, getFID, getFCP, getLCP, getTTFB} from 'web-vitals';
getCLS(console.log);
getFID(console.log);
getFCP(console.log);
getLCP(console.log);
getTTFB(console.log);
Synthetic Monitoring
- Lighthouse CI for automated testing
- WebPageTest for detailed analysis
- Performance budgets in build process
- Regular performance audits
Mobile Performance
Mobile-Specific Optimizations
- Optimize for slower CPUs and networks
- Minimize JavaScript execution time
- Use appropriate image sizes for mobile
- Implement touch-friendly interactions
Progressive Web App Features
- Service worker for offline functionality
- App shell architecture
- Background sync for data updates
- Push notifications for engagement
Performance Budget
Setting Budgets
- Total page weight: < 1.5MB
- JavaScript bundle: < 500KB
- Images: < 800KB
- LCP: < 2.5 seconds
- FID: < 100 milliseconds
Enforcement
// Webpack bundle analyzer
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false,
reportFilename: 'bundle-report.html'
})
]
};
Tools and Resources
Performance Testing Tools
- Google Lighthouse
- WebPageTest
- GTmetrix
- Pingdom
- Chrome DevTools
Optimization Tools
- Image optimizers (like our image converter)
- CSS and JS minifiers
- Bundle analyzers
- Performance monitoring services
Web performance optimization is an ongoing process that requires continuous monitoring and improvement. By implementing these strategies systematically, you can significantly improve your website's speed, user experience, and business outcomes.