Middle+
How do you optimize website performance?
sobes.tech AI
Answer from AI
- Image optimization:
- Using modern formats like WebP.
- Compressing images without quality loss.
- Lazy loading for images outside the visible area.
- Responsive images using
<picture>orsrcset.
- Minification and compression of resources:
- Minifying HTML, CSS, and JavaScript.
- Gzip or Brotli compression for text resources.
- Caching:
- Browser caching using HTTP headers (
Cache-Control,Expires). - Server-side caching.
- Using Service Workers for offline access and more complex caching.
- Browser caching using HTTP headers (
- Critical rendering path optimization:
- Deferred loading of non-critical CSS and JavaScript.
- Asynchronous script loading (
async,defer). - Inline critical CSS.
- Reducing HTTP requests:
- Combining CSS and JavaScript files (with caution in HTTP/2).
- Using sprites for small icons.
- Embedding small resources (like fonts or SVGs) into CSS using data URIs.
- Font optimization:
- Using modern font formats (WOFF2).
- Hosting fonts locally.
- Preloading fonts (
preload). - Using
font-displayto control font rendering during load.
- JavaScript performance:
- Optimizing algorithms and data structures.
- Reducing DOM operations.
- Using event delegation.
- Code splitting.
- Rendering and painting optimization:
- Avoiding expensive CSS properties and styles.
- Using
will-change. - Optimizing animations and transitions.
- Using CDN (Content Delivery Network).
- Server-side optimization:
- Fast server response.
- Optimizing database queries.
// Example of lazy loading an image
const images = document.querySelectorAll('img[data-src]');
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
delete img.dataset.src;
observer.unobserve(img);
}
});
});
images.forEach(image => {
observer.observe(image);
});
<!-- Example of using async and defer for scripts -->
<script src="script1.js" async></script>
<script src="script2.js" defer></script>
/* Example of using font-display */
@font-face {
font-family: 'MyFont';
src: url('myfont.woff2') format('woff2');
font-display: swap; /* Allows the browser to use a fallback font while the main font loads */
}