Page speed is one of the few optimizations where every improvement directly impacts your bottom line. Google has confirmed page speed as a ranking factor. Studies consistently show that a 1-second improvement in load time increases conversions by 3–7%. For e-commerce sites, 100ms of latency can cost millions in revenue at scale. For everyone else, a slow site means higher bounce rates, lower engagement, and worse search rankings.

The good news: most of the biggest speed wins are relatively straightforward to implement. This guide covers 15 concrete techniques, ordered roughly by impact-to-effort ratio. Start at the top, work your way down, and you'll see measurable improvements in Google PageSpeed Insights, Lighthouse, and real user experience.


Understanding the Metrics That Matter

Before optimizing, you need to measure. Google's Core Web Vitals are the current standard for page experience measurement:

Metric What It Measures Good Threshold
LCP — Largest Contentful PaintWhen the largest visible element loads≤ 2.5 seconds
INP — Interaction to Next PaintResponsiveness to user interactions≤ 200ms
CLS — Cumulative Layout ShiftVisual stability (elements jumping around)≤ 0.1
TTFB — Time to First ByteServer response time≤ 800ms
FCP — First Contentful PaintWhen the first content appears on screen≤ 1.8 seconds
TTI — Time to InteractiveWhen the page becomes fully interactive≤ 3.8 seconds

Use these tools to measure before and after each optimization:


1 Optimize and Compress Images

Images are typically the largest assets on any web page, often accounting for 60–80% of total page weight. This is almost always the highest-impact optimization available.

Choose the Right Format

FormatBest ForNotes
WebPPhotos, complex images25–34% smaller than JPEG, with transparency support. Use as primary format.
AVIFPhotosEven better compression than WebP. Newer browser support — use with fallback.
SVGLogos, icons, illustrationsInfinitely scalable, tiny file size for vector graphics.
PNGScreenshots, images requiring exact transparencyLossless but large. Use only when needed.
JPEGPhotos (legacy)Fallback when WebP/AVIF aren't supported.

Implement with the HTML picture Element

<picture>
  <source srcset="hero.avif" type="image/avif">
  <source srcset="hero.webp" type="image/webp">
  <img src="hero.jpg" alt="Hero image" width="1200" height="600">
</picture>

Set Explicit Width and Height

Always include width and height attributes on images. The browser reserves space before the image loads, eliminating layout shift (CLS).

Compression Tools

# Convert to WebP with cwebp
cwebp -q 80 image.jpg -o image.webp

# Batch convert all JPEGs in a directory
for f in *.jpg; do cwebp -q 80 "$f" -o "${f%.jpg}.webp"; done

2 Enable Lazy Loading for Images and Iframes

Lazy loading defers the download of off-screen images until the user scrolls near them. This dramatically reduces initial page weight and speeds up the above-the-fold experience — which is all that matters for LCP and FCP.

<!-- Lazy load off-screen images -->
<img src="photo.webp" alt="..." loading="lazy" width="800" height="600">

<!-- Eager load above-the-fold hero images (never lazy-load these) -->
<img src="hero.webp" alt="Hero" loading="eager" width="1200" height="600">

<!-- Lazy load iframes (YouTube embeds, maps, etc.) -->
<iframe src="https://www.youtube.com/embed/abc123" loading="lazy"></iframe>
Important: Never lazy-load the LCP image (the first large image visible in the viewport). Lazy loading it delays the most important paint on the page and tanks your LCP score. Apply loading="lazy" only to images below the fold.

Preload Your LCP Image Instead

<!-- In <head>: preload the hero image so it downloads as early as possible -->
<link rel="preload" as="image" href="hero.webp" type="image/webp">

3 Use a Content Delivery Network (CDN)

A CDN stores copies of your static assets (images, CSS, JavaScript, fonts) on servers around the world. When a user requests your page, assets are served from the nearest edge location — potentially reducing latency from 200ms to 20ms.

What to Serve from a CDN

Popular CDN Options

For most sites, simply putting Cloudflare in front of your origin server (free tier) will measurably improve load times globally with minimal configuration.


4 Implement Browser Caching with Proper Cache Headers

Cache headers tell browsers (and CDN edge nodes) how long to store a file locally before re-fetching it. A properly cached JavaScript bundle loads in 0ms on repeat visits — it never leaves the user's disk.

Cache-Control Strategies

# Nginx: aggressive caching for versioned assets
location ~* \.(js|css|woff2|png|webp|avif|jpg|svg)$ {
    expires 1y;
    add_header Cache-Control "public, max-age=31536000, immutable";
}

# Apache: same via .htaccess
<FilesMatch "\.(js|css|woff2|png|webp|jpg|svg)$">
    Header set Cache-Control "public, max-age=31536000, immutable"
</FilesMatch>

# HTML files: short cache + revalidation
location ~* \.html$ {
    add_header Cache-Control "public, max-age=300, must-revalidate";
}

Cache Busting with Content Hashing

Use a build tool (Webpack, Vite, Parcel) to append a content hash to filenames. When the file changes, the filename changes, and browsers automatically fetch the new version:

# Without cache busting (problematic)
style.css

# With content hashing (correct approach)
style.a3f9b2c1.css
main.7d8e2f0a.js

With content hashing, you can safely set a 1-year cache lifetime. The browser will use the cached version forever — until your build tool generates a new hash because the content changed.


5 Minify CSS, JavaScript, and HTML

Minification removes whitespace, comments, and unnecessary characters from source files without changing their behavior. A 100KB JavaScript file can shrink to 60–70KB after minification alone.

# Minify CSS with cssnano (via PostCSS)
npx postcss styles.css --use cssnano -o styles.min.css

# Minify JavaScript with Terser
npx terser app.js -o app.min.js --compress --mangle

# Minify HTML with html-minifier
npx html-minifier-terser --collapse-whitespace --remove-comments \
  --minify-css --minify-js -o index.min.html index.html

If you use a modern bundler (Vite, Webpack, Parcel, esbuild), minification is typically enabled automatically in production mode:

# Vite: automatically minifies in production
vite build

# esbuild: explicit minification flags
esbuild app.js --bundle --minify --outfile=app.min.js

6 Enable Compression (Gzip / Brotli)

Text-based assets (HTML, CSS, JavaScript, JSON, SVG) compress extremely well. Brotli typically achieves 20–26% better compression than Gzip. Enable both on your server and serve Brotli to browsers that support it.

# Nginx: enable Brotli and Gzip
# (requires ngx_brotli module)
brotli on;
brotli_comp_level 6;
brotli_types text/html text/css application/javascript application/json image/svg+xml;

gzip on;
gzip_vary on;
gzip_comp_level 5;
gzip_types text/html text/css application/javascript application/json image/svg+xml;

# Apache: enable mod_deflate for Gzip
<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>

Verify compression is working:

curl -I -H "Accept-Encoding: br,gzip" https://yoursite.com/app.js | grep content-encoding
# Should return: content-encoding: br  (or gzip)

7 Eliminate Render-Blocking Resources

By default, the browser stops parsing HTML whenever it encounters a <script> or <link rel="stylesheet"> tag, waiting for the resource to fully download before continuing. This blocks rendering and is one of the main causes of slow FCP.

Defer Non-Critical JavaScript

<!-- Blocking (bad for performance) -->
<script src="app.js"></script>

<!-- Deferred: downloads in parallel, executes after HTML parse completes -->
<script src="app.js" defer></script>

<!-- Async: downloads in parallel, executes immediately when ready (no order guarantee) -->
<!-- Use for independent analytics/tracking scripts -->
<script src="analytics.js" async></script>

Extract and Inline Critical CSS

Critical CSS is the minimal set of styles needed to render the above-the-fold content. Inline it in <style> tags in the <head> and lazy-load the rest:

<head>
  <!-- Inline critical CSS (extracted by a tool like Critters or critical) -->
  <style>
    /* ... above-the-fold styles only ... */
    body { font-family: sans-serif; margin: 0; }
    header { background: #000; color: #fff; padding: 1rem; }
  </style>

  <!-- Load full stylesheet without blocking render -->
  <link rel="preload" href="styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
  <noscript><link rel="stylesheet" href="styles.css"></noscript>
</head>

8 Optimize Web Fonts

Fonts are a sneaky performance drain. A single font family in multiple weights can add 300–500KB to your page. Worse, browsers often block text rendering until the font loads (Flash of Invisible Text — FOIT).

Use font-display: swap

@font-face {
  font-family: 'Inter';
  src: url('inter.woff2') format('woff2');
  font-display: swap; /* Show fallback text immediately, swap when font loads */
}

Subset Your Fonts

Most font files contain characters for dozens of languages. If your site is in English, you only need the Latin character set. Use pyftsubset (from fonttools) or an online tool to strip unused glyphs:

# Subset to Latin characters only (reduces file size by ~70%)
pyftsubset Inter.ttf --unicodes="U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC" \
  --flavor=woff2 --output-file=Inter-latin.woff2

Preload Critical Fonts

<link rel="preload" href="/fonts/inter-regular.woff2" as="font" type="font/woff2" crossorigin>

Use the System Font Stack as a Fallback

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

For many sites, the native system font stack looks excellent and eliminates font loading entirely.


9 Reduce Time to First Byte (TTFB)

TTFB measures the time from when the browser sends an HTTP request to when it receives the first byte of the response. A high TTFB means your server is slow — and nothing else will fix that except improving server response time.

Cache Dynamic Pages at the Server or Edge

# Nginx: simple page cache for WordPress-style sites
fastcgi_cache_path /tmp/nginx_cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";

server {
  location ~ \.php$ {
    fastcgi_cache WORDPRESS;
    fastcgi_cache_valid 200 60m;
    fastcgi_cache_bypass $no_cache;
  }
}

Upgrade PHP / Application Runtime

Use Database Query Caching

# Redis-based caching (Python/Django example)
from django.core.cache import cache

def get_posts():
    posts = cache.get('homepage_posts')
    if posts is None:
        posts = Post.objects.select_related('author').order_by('-created')[:10]
        cache.set('homepage_posts', posts, timeout=300)  # Cache for 5 minutes
    return posts

10 Implement HTTP/2 or HTTP/3

HTTP/1.1 loads resources sequentially — browsers can only open 6 connections per domain. HTTP/2 multiplexes multiple requests over a single connection, eliminating head-of-line blocking. HTTP/3 (over QUIC) goes further, eliminating TCP connection overhead entirely.

# Check which protocol your site is using
curl -I --http2 https://yoursite.com 2>&1 | grep "HTTP/"
# Should show: HTTP/2 200

# Or use:
curl -sI https://yoursite.com | grep -i "^HTTP/"

Enabling HTTP/2 in Nginx

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    # ... rest of config
}

HTTP/2 requires HTTPS. If you haven't set up a TLS certificate yet, use Let's Encrypt (Certbot) — it's free and takes 10 minutes to configure.

Note: With HTTP/2, the old advice to "bundle all JavaScript into one file" is less important. HTTP/2 handles multiple smaller files efficiently. You can use code splitting more aggressively.

11 Use Resource Hints

Resource hints tell the browser about resources it'll need soon, so it can start fetching them early — before it even encounters them in the HTML.

<head>
  <!-- preconnect: establish TCP+TLS connection to a third-party origin early -->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://cdn.yoursite.com" crossorigin>

  <!-- dns-prefetch: resolve DNS for third-party domains (fallback for older browsers) -->
  <link rel="dns-prefetch" href="https://api.analytics.com">

  <!-- preload: download a critical resource ASAP -->
  <link rel="preload" href="hero.webp" as="image">
  <link rel="preload" href="inter-regular.woff2" as="font" type="font/woff2" crossorigin>
  <link rel="preload" href="critical.css" as="style">

  <!-- prefetch: download a resource you'll likely need on the NEXT page -->
  <link rel="prefetch" href="/next-page.html">
</head>

Use preconnect sparingly — establishing and maintaining idle connections has a cost. Limit to 2–3 of your most critical third-party origins.


12 Remove Unused CSS and JavaScript

The average web page loads hundreds of kilobytes of CSS it never uses. CSS frameworks like Bootstrap, Tailwind (without purging), and Bulma contain thousands of unused rules by default.

Audit Unused CSS with Chrome DevTools

Open Chrome DevTools → press Ctrl+Shift+P → type "Coverage" → select "Show Coverage". Load your page and see exactly which CSS/JS bytes are used vs. unused.

Purge Unused CSS with PurgeCSS

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

# postcss.config.js
module.exports = {
  plugins: [
    require('@fullhuman/postcss-purgecss')({
      content: ['./src/**/*.html', './src/**/*.js'],
      safelist: ['active', 'show', 'modal-open'] // Classes added dynamically
    })
  ]
}

Tree-Shaking for JavaScript

// Bad: imports the entire lodash library (~70KB gzipped)
import _ from 'lodash';
const result = _.debounce(fn, 300);

// Good: imports only the function you need (<1KB)
import debounce from 'lodash/debounce';
const result = debounce(fn, 300);

Modern bundlers like Vite and Rollup perform tree-shaking automatically — but only for ES modules (import/export), not CommonJS (require()).


13 Code Split Your JavaScript

Loading your entire JavaScript bundle upfront forces users to download code they may never execute. Code splitting breaks the bundle into chunks that load on demand.

// Vite / Webpack: dynamic import() creates an automatic code split point
// The checkout module only loads when the user clicks "Checkout"
button.addEventListener('click', async () => {
  const { initCheckout } = await import('./checkout.js');
  initCheckout();
});

// React: lazy-load route components
import { lazy, Suspense } from 'react';
const Dashboard = lazy(() => import('./Dashboard'));
const Settings = lazy(() => import('./Settings'));

function App() {
  return (
    <Suspense fallback={<Spinner />}>
      <Routes>
        <Route path="/dashboard" element={<Dashboard />} />
        <Route path="/settings" element={<Settings />} />
      </Routes>
    </Suspense>
  );
}

A well-split application might load only 30–50KB of JavaScript on the initial page, with additional chunks loading only when needed.


14 Optimize Third-Party Scripts

Third-party scripts — analytics, chat widgets, ad networks, A/B testing tools, social share buttons — are often the biggest performance killers on a page. They execute code you don't control, can block the main thread, and add DNS lookups for external origins.

Audit Your Third-Party Scripts

Open WebPageTest or Chrome DevTools Network tab and look at the timeline. Identify which third-party scripts are taking the longest or blocking other resources.

Load Third-Party Scripts Async

<!-- Never load analytics synchronously -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXX"></script>

<!-- Defer non-critical widgets until after page load -->
<script>
  window.addEventListener('load', function() {
    var script = document.createElement('script');
    script.src = 'https://cdn.chatwidget.com/widget.js';
    document.body.appendChild(script);
  });
</script>

Self-Host What You Can

Self-hosting fonts and analytics scripts eliminates the DNS lookup and connection overhead to third-party origins:

<!-- Instead of loading Google Fonts from googleapis.com -->
<link href="https://fonts.googleapis.com/css2?family=Inter" rel="stylesheet">

<!-- Download and host the font yourself -->
<link href="/fonts/inter.css" rel="stylesheet">

Use Facade Patterns for Heavy Embeds

A YouTube embed loads 500KB+ of resources even when the video is never played. Load a static preview image instead, and only load the actual embed when the user clicks play:

<!-- Lite YouTube Embed (click to load the actual player) -->
<lite-youtube videoid="dQw4w9WgXcQ"></lite-youtube>
<script src="https://cdn.jsdelivr.net/npm/@paulirish/lite-youtube-embed"></script>

15 Fix Cumulative Layout Shift (CLS)

Layout shift happens when elements on the page move unexpectedly after the initial paint — images loading without reserved space, dynamically injected banners pushing content down, fonts swapping with different metrics. Even 0.1 CLS can feel jarring to users.

Reserve Space for Images and Video

<!-- Always include explicit width and height -->
<img src="photo.webp" width="800" height="533" alt="...">

<!-- Or use aspect-ratio in CSS -->
.hero-image {
  aspect-ratio: 16 / 9;
  width: 100%;
}

<!-- Video with reserved aspect ratio -->
.video-container {
  position: relative;
  padding-bottom: 56.25%; /* 16:9 */
  height: 0;
}
.video-container iframe {
  position: absolute;
  top: 0; left: 0;
  width: 100%; height: 100%;
}

Avoid Inserting Content Above Existing Content

Cookie banners, notification bars, and ads that load dynamically and push content down are major CLS contributors. Reserve space for these elements in the initial HTML layout, even if they're empty at first, so they don't cause shifts when they load.

Use font-display: optional for Non-Critical Fonts

@font-face {
  font-family: 'Decorative';
  src: url('decorative.woff2') format('woff2');
  /* optional: if font doesn't load in time, use fallback forever (no swap = no shift) */
  font-display: optional;
}

Measuring Your Results

After implementing these techniques, measure your before/after scores across multiple dimensions:

# Test from the command line with Lighthouse CI
npm install -g @lhci/cli
lhci autorun --collect.url=https://yoursite.com

# WebPageTest via API
curl "https://www.webpagetest.org/runtest.php?url=https://yoursite.com&f=json&k=YOUR_KEY"
TechniquePrimary Metric ImprovedEffort
Image optimization & formatLCP, page weightLow
Lazy loading imagesFCP, page weightVery low
CDNTTFB, all metricsLow–Medium
Browser cachingRepeat load timeLow
MinificationFCP, TTIVery low (automated)
Compression (Brotli)FCP, TTILow
Eliminate render-blockingFCP, LCPMedium
Font optimizationFCP, CLSMedium
Reduce TTFBTTFB, all metricsMedium–High
HTTP/2All metricsLow
Resource hintsFCP, LCPLow
Remove unused CSS/JSFCP, TTIMedium
Code splittingTTI, INPMedium–High
Third-party scriptsTTI, INPMedium
Fix CLSCLSLow–Medium

Summary

Website speed optimization isn't a one-time task — it's an ongoing practice. Start with image optimization and lazy loading (techniques 1 and 2) because they're the highest-impact, lowest-effort changes available on almost every site. Then implement proper caching and a CDN. Those three steps alone will visibly improve your scores.

Work down the list as time allows. Each technique compounds on the others. A site that implements all 15 will typically score 90+ on Google PageSpeed Insights across both mobile and desktop — and more importantly, real users will feel the difference.

Use the DNS Lookup Tool to verify your CDN and DNS propagation during a migration, and the REST API Tester to verify your API endpoints are responding within your performance budget.