I've watched hundreds of site owners chase a perfect PageSpeed score while their actual users wait three seconds for a hero image to load. The score is a proxy. Load time is what matters.
This guide covers the production fixes that move the needle: optimizing images, tuning cache headers, deferring JavaScript, reducing server response time, and cleaning up database queries. I'll also call out the anti-patterns that waste time—like obsessing over eliminating every render-blocking resource when your real problem is an unoptimized 4MB hero image.
Why PageSpeed scores mislead you
PageSpeed Insights runs a synthetic test from a data center. It doesn't reflect your actual user base, their devices, or their network conditions. A score of 95 on desktop means nothing if your mobile users on 4G see a six-second LCP.
Focus on Core Web Vitals instead: Largest Contentful Paint (LCP), First Input Delay (FID), and Cumulative Layout Shift (CLS). These metrics correlate with real user experience. Everything else is secondary.
In support tickets I handled, the usual culprit was a single unoptimized asset—a full-resolution PNG hero image, a bloated JavaScript bundle, or a slow database query on the homepage. Fix the bottleneck first. Then optimize around the edges.
Optimize images properly
Images are the easiest win and the most commonly ignored one.
Serve WebP or AVIF with a JPEG fallback. Most CDNs and image optimization plugins handle this automatically now. If you're on a VPS without a CDN, install libwebp and convert images at upload time using ImageMagick or a build script.
Resize images to the dimensions they're actually displayed at. A 2400px-wide hero image displayed at 1200px wastes bandwidth. Use responsive images with srcset and let the browser pick the right size:
<img
src="hero-800.webp"
srcset="hero-400.webp 400w, hero-800.webp 800w, hero-1200.webp 1200w"
sizes="(max-width: 600px) 400px, (max-width: 1200px) 800px, 1200px"
alt="Hero image"
width="1200"
height="675"
/>
Always set width and height attributes. This prevents layout shift as images load.
Lazy-load images below the fold. Add loading="lazy" to any <img> tag that isn't immediately visible. Do not lazy-load your hero image or anything in the viewport on load—this delays LCP.
What not to do
Don't compress images so aggressively that they look terrible. Quality 75-85 for JPEG and quality 80-90 for WebP strikes the right balance. Check the visual result on a high-DPI display before deploying.
Don't rely solely on a WordPress plugin to fix everything. Plugins like ShortPixel and Imagify help, but they can't fix architectural problems like serving full-resolution images from the media library. Resize on upload or during a build step.
Fix server response time
Time to First Byte (TTFB) should be under 600ms. Anything over a second points to a server or application problem.
Check your slow query log first. On MySQL, enable it in my.cnf:
[mysqld]
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1
Restart MySQL and monitor the log. Any query taking over a second on page load is a problem. Add indexes or refactor the query.
For WordPress, install Query Monitor in staging and profile the homepage. Look for plugins that run expensive queries on every page load—logging plugins, analytics plugins, and page builders are common offenders. Disable or replace them.
Upgrade to PHP 8.1 or newer if you haven't already. PHP 7.4 reached end-of-life and is significantly slower. On cPanel, you can switch PHP versions under MultiPHP Manager. On a VPS, install the latest version from the package repository and update your Nginx or Apache config.
Increase opcache.memory_consumption and opcache.max_accelerated_files in php.ini. Start with 256MB and 10000 files. This caches compiled PHP bytecode and eliminates redundant parsing.
opcache.enable=1
opcache.memory_consumption=256
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60
Restart PHP-FPM after making changes.
Use aggressive cache headers
Set long cache lifetimes for static assets: CSS, JavaScript, fonts, and images. A year is standard.
In Nginx:
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2|woff|ttf)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
In Apache, add this to .htaccess:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType font/woff2 "access plus 1 year"
</IfModule>
For HTML, use a shorter lifetime—10 minutes to an hour—so content updates propagate quickly. If you're running WordPress with a page cache plugin like WP Rocket or LiteSpeed Cache, the plugin handles this.
Cache-busting is critical. When you update a stylesheet or script, the filename or query string must change, or browsers will serve the stale cached version. Most build tools (Webpack, Vite, Parcel) add a hash to filenames automatically. WordPress themes should enqueue scripts with a version parameter:
wp_enqueue_style('main-style', get_stylesheet_uri(), array(), '1.2.3');
Defer and async JavaScript strategically
Blocking JavaScript delays rendering. Move script tags to the bottom of the page or add defer or async attributes.
Use defer for scripts that need to run in order and don't need to execute immediately:
<script src="/assets/main.js" defer></script>
Use async for independent scripts like analytics:
<script src="https://www.google-analytics.com/analytics.js" async></script>
Don't defer JavaScript that's required for above-the-fold interactivity. If your hero carousel or mobile menu depends on a script, load it synchronously or inline a small critical script.
Inline critical CSS
Extract the CSS needed to render above-the-fold content and inline it in a <style> tag in the <head>. Load the rest of your stylesheet asynchronously.
Tools like Critical or Penthouse can extract critical CSS automatically. For WordPress, plugins like WP Rocket and Autoptimize include this feature. Test thoroughly—inlining the wrong CSS breaks layouts.
So what if your database is slow?
WordPress queries can dominate page load time, especially on shared hosting with limited resources. Check your database size first:
mysql -u root -p -e "SELECT table_schema AS 'Database', ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS 'Size (MB)' FROM information_schema.tables GROUP BY table_schema;"
If wp_options is over 10MB, you likely have autoloaded data bloat. Query the autoloaded options:
SELECT SUM(LENGTH(option_value)) as autoload_size FROM wp_options WHERE autoload='yes';
Autoloaded data under 1MB is fine. Over 3MB is a problem. Find the largest entries:
SELECT option_name, LENGTH(option_value) as option_size FROM wp_options WHERE autoload='yes' ORDER BY option_size DESC LIMIT 20;
Plugins that store large transients or cache data in wp_options are common offenders. Disable or replace them. For transients, move to Redis or Memcached instead.
Clean up post revisions, trashed posts, and spam comments. Install WP-Optimize or run these queries manually:
DELETE FROM wp_posts WHERE post_type = 'revision';
DELETE FROM wp_posts WHERE post_status = 'trash';
DELETE FROM wp_comments WHERE comment_approved = 'spam';
Optimize tables afterward:
OPTIMIZE TABLE wp_posts, wp_postmeta, wp_options, wp_comments;
Enable compression
Gzip or Brotli compression reduces payload size by 70-80% for text-based assets.
In Nginx, enable Gzip:
gzip on;
gzip_vary on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript;
gzip_min_length 1000;
Brotli offers better compression but requires the ngx_brotli module. If you control your VPS, compile Nginx with Brotli support or use a pre-built package.
In Apache, enable mod_deflate:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
</IfModule>
Check compression is working:
curl -I -H "Accept-Encoding: gzip" https://yoursite.com
Look for Content-Encoding: gzip in the response headers.
Avoid these common anti-patterns
Eliminating render-blocking resources entirely is not always feasible or beneficial. Some CSS and JavaScript must load before the page renders. Don't waste time trying to defer every resource when your real problem is a 3-second TTFB.
Disabling all plugins to "improve performance" is not a strategy. Identify which plugins slow your site using Query Monitor or server logs, then disable or replace only those.
Using too many optimization plugins creates conflicts and adds overhead. Pick one caching plugin, one image optimizer, and one minifier. More is not better.
Chasing a perfect score while ignoring real user metrics is vanity work. Open Google Search Console and check your Core Web Vitals report. If 90% of your URLs pass, you're done. If most fail, focus on LCP and CLS first.
Use a CDN for static assets
A CDN caches static files at edge locations close to your users. This reduces latency and offloads traffic from your origin server.
Cloudflare is the easiest option for most hosting setups. Point your domain's nameservers to Cloudflare, enable caching for static assets, and configure page rules to cache HTML if your site is mostly static.
For WordPress, install the Cloudflare plugin and configure cache purging on post updates. Without automatic purging, stale content will frustrate you.
BunnyCDN and KeyCDN are lighter alternatives if you only need asset caching and don't want a full proxy in front of your origin.
Profile before optimizing
Run PageSpeed Insights, but also check WebPageTest with a real device profile and network throttling. WebPageTest shows a waterfall chart that reveals which assets block rendering and how long each takes to load.
Use Chrome DevTools Performance tab to record a page load. Look at the flame chart. Long tasks blocking the main thread point to expensive JavaScript. Layout shifts highlight missing dimensions or dynamically injected content.
Check server logs and application performance monitoring if available. New Relic, Datadog, and Blackfire can pinpoint slow database queries and PHP bottlenecks that synthetic tests miss.
What to check first
Start with the biggest bottleneck. Run PageSpeed Insights and look at the opportunities list. If "Properly size images" saves three seconds, fix that before optimizing font loading.
Measure TTFB. If it's over a second, profile your database and application layer before touching the front end.
Check real user data in Search Console. If your mobile LCP is consistently bad but desktop is fine, the problem is image size or network latency, not your JavaScript bundle.
Optimization is not a one-time task. Traffic patterns change, plugins get updated, and new content gets added. Set up monitoring and revisit every quarter.
Common questions
Q: Should I defer all JavaScript?
No. Defer scripts that aren't needed for initial render. If a script provides critical interactivity above the fold, load it synchronously or inline it.
Q: Will a CDN fix my slow TTFB?
Not directly. A CDN caches static assets but doesn't improve server response time for dynamic requests. Fix slow queries and upgrade PHP first.
Q: Is a PageSpeed score of 90 good enough?
Scores don't matter. Real user Core Web Vitals do. Check Search Console for actual LCP, FID, and CLS data.
Q: Can I optimize without a staging site?
You can, but it's risky. Aggressive caching, deferred scripts, and database changes can break functionality. Test in staging first.
Q: Do I need a separate image CDN?
Not necessarily. If you're already using Cloudflare or another CDN with image optimization, that's sufficient. A dedicated image CDN like Cloudinary helps if you need advanced transformations or automatic format conversion.
Test, measure, repeat
Optimization is iterative. Make one change, measure the impact, and move to the next bottleneck. Batch changes obscure what actually helped.
Use real user monitoring to track performance over time. Synthetic tests catch regressions, but RUM data shows how real users experience your site.
Keep backups before making changes. A misconfigured cache rule or bad database query can take your site down. Test in staging, deploy to production, and monitor for errors.
