How to Fix Core Web Vitals and Speed Up a Slow WordPress Site

Slow loading times and poor visual stability kill conversion rates. When Google shifted to Core Web Vitals (CWV) as a ranking factor, optimization became a technical necessity.

This guide details the exact production-tested workflow I use to optimize client websites, taking them from failing grades to green scores.


Phase 1: Establish the Baseline

Before changing a single line of code, measure your current performance. Do not rely solely on your local Lighthouse scores; they use your fast development machine and network. Use PageSpeed Insights (PSI) to capture both real-world Field Data (Chrome User Experience Report) and synthetic Lab Data.

Performance Target Metrics

Metric Metric Name Poor (Before) Good (Target After)
TTFB Time to First Byte > 1.0s < 0.2s
LCP Largest Contentful Paint > 4.0s < 2.5s
CLS Cumulative Layout Shift > 0.25 < 0.10
INP Interaction to Next Paint > 500ms < 200ms

Phase 2: Step-by-Step Optimization Workflow

1. Reduce TTFB (Server and Database)

TTFB is the foundation of all other speed metrics. If your server takes 1 second to respond, your LCP can never be under 1 second.

  • Database Cleanup: Over time, databases accumulate overhead, expired transients, and spam comments. Run these SQL commands to clean up a WordPress database: sql DELETE FROM wp_options WHERE option_name LIKE '_transient_%'; DELETE FROM wp_comments WHERE comment_approved = 'spam'; DELETE FROM wp_postmeta WHERE meta_key = '_edit_lock' OR meta_key = '_edit_last';
  • Object Caching: Install Redis or Memcached on your server to store database query results in RAM.
  • Nginx FastCGI Caching: Bypass PHP execution entirely for guest users by caching HTML directly in Nginx. Add this to your Nginx virtual host configuration: nginx fastcgi_cache_path /etc/nginx/cache levels=1:2 keys_zone=MYAPP:100m inactive=60m; fastcgi_cache_key "$scheme$request_method$host$request_uri";

2. Optimize Images and Implement AVIF

Images are almost always the primary cause of poor LCP.

  • Format Conversion: Convert all PNG/JPG images to AVIF (preferred) or WebP. AVIF offers up to 50% better compression than JPEG at equivalent quality. Use the CLI tool sharp to batch convert images in your terminal: bash npx sharp-cli -i ./images/*.jpg -o ./dist/ -f avif --quality 75
  • Modern Markup: Use the <picture> element to serve AVIF with fallback support: html <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="630" fetchpriority="high"> </picture>
  • Preloading LCP: Never lazy-load your LCP image. Instead, preload it in your HTML <head>: html <link rel="preload" fetchpriority="high" as="image" href="hero.avif" type="image/avif">

3. Implement Critical CSS and Defer Non-Critical Assets

Render-blocking CSS and JS delay the browser from painting the screen.

  • Extract Critical CSS: Identify the CSS required to style the above-the-fold content. Use NPM packages like critical to automate this: bash npx critical index.html --base dist/ --inline > index-optimized.html
  • Defer Remaining CSS: Load the rest of your CSS asynchronously: html <link rel="rel" href="style.css" as="style" onload="this.rel='stylesheet'"> <noscript><link rel="stylesheet" href="style.css"></noscript>
  • Defer JavaScript: Move non-essential scripts to the footer and apply defer or async attributes: html <script src="analytics.js" defer></script>

4. Eliminate Cumulative Layout Shift (CLS)

CLS occurs when elements move on the screen while the page is loading.

  • Explicit Dimensions: Always define width and height attributes on <img> and <iframe> elements to reserve space in the layout: html <img src="logo.svg" width="180" height="60" alt="Logo">
  • CSS Aspect Ratio: For responsive elements, use the CSS aspect-ratio property: css .card-image { aspect-ratio: 16 / 9; width: 100%; height: auto; }
  • Avoid Dynamic Content Shifts: Never insert dynamic content (like ads or cookie banners) above existing content unless triggered by user interaction.

5. Improve Interaction to Next Paint (INP)

INP measures page responsiveness. It is driven by heavy JavaScript execution blocking the main thread.

  • Break Up Long Tasks: Any JS task taking longer than 50ms is a "long task." Use requestIdleCallback or setTimeout to yield back to the main thread: ```javascript function yieldToMain() { return new Promise(resolve => setTimeout(resolve, 0)); }

    async function processHeavyData(data) { for (let item of data) { process(item); await yieldToMain(); // Yields control back to the browser to handle user input } } ``` * Replace Heavy Libraries: Swap heavy dependencies for lighter alternatives (e.g., swap Moment.js for Day.js, or jQuery for native vanilla JS).

6. Configure CDN and Edge Caching

Deploying a CDN brings your assets physically closer to your users.

  • Cloudflare Cache Everything: Set up a Page Rule on Cloudflare to cache static HTML pages at the edge.
  • Configure Cache-Control Headers: Instruct browsers and CDNs to cache static assets for a long duration: nginx location ~* \.(js|css|png|jpg|jpeg|gif|ico|woff2|avif)$ { expires 1y; add_header Cache-Control "public, no-transform"; }

Phase 3: Implementation Checklist

Follow this checklist for every deployment:

  • [ ] Measure: Run a baseline PageSpeed Insights test.
  • [ ] Database: Run cleanup queries and enable Redis object caching.
  • [ ] Images: Convert all assets to AVIF/WebP and add explicit width/height attributes.
  • [ ] LCP: Preload the hero image and set fetchpriority="high". Disable lazy-loading for above-the-fold assets.
  • [ ] CSS: Generate critical CSS and inline it into the HTML <head>.
  • [ ] JS: Defer all non-critical scripts. Check for long tasks in Chrome DevTools Performance panel.
  • [ ] CDN: Enable Cloudflare proxy and configure aggressive Cache-Control headers.
  • [ ] Verify: Re-run PageSpeed Insights to confirm improvements.

Common Optimization Mistakes

  • Lazy-loading everything: Applying loading="lazy" to your LCP image delays its loading, which directly damages your LCP score.
  • Over-optimizing with too many plugins: Installing multiple optimization plugins on platforms like WordPress often creates conflicts, double-minifies scripts, and actually degrades performance.
  • Ignoring mobile emulation: Optimizing solely for desktop. Mobile devices have significantly weaker CPUs and slower network connections; always optimize using a "Mid-tier mobile" profile in Chrome DevTools.

Need this done for you?

Optimizing Core Web Vitals requires deep technical knowledge of server configurations, asset pipelines, and rendering paths. If you want to skip the trial-and-error and get guaranteed green scores for your website, let's work together.

Hire me on Freelancehunt to audit, optimize, and speed up your web project today.

Originally posted at https://guardlabs.online/care/

Комментарии

Популярные сообщения из этого блога

I shipped a 12-question crypto security audit in 2 hours