WordPress Performance Improvements – 3/3 (PageSpeed Audits)

This is the third part of the WordPress Performance Improvement series; visit links to find the first and second parts.

31. Ensure text remains visible during Webfont load

Browsers can not render the text until that web font is downloaded and ready to render. Unfortunately, most of the time, text on the page is fully downloaded before web fonts are. In such a scenario, the text remains hidden until web font is downloaded; this is called Flash of Invisible Text (FOIT).

By ensuring that text is visible during web font download, you improve the page experience for users. Users don’t see the empty screen, plus it reduces the layout shift.

Pagespeed shows the following suggestions for any Webfont URL that may cause FOIT.

Ensure text remains visible during Webfont load
web.dev

How to avoid showing invisible text? 

  • You can avoid FOIT in most modern browsers by temporarily showing system font with the addition of font-display:swap in your @font-face style.
                    

@font-face {
font-family: "Pacifico";
font-style: normal;
font-weight: 400;
src: local("Pacifico Regular"),
local("Pacifico-Regular"),
url("https://fonts.gstatic.com/s/pacifico/v12/FwZY7-Qmy14u9lezJ-6H6MmBp0u-.woff2") format("woff2");
font-display: swap;
}

swap tells the browser to display text immediately using a system font; once the web font is ready, it replaces the system font. 

  • Preload web fonts

Use <link rel=”preload” as=”font”> to reload the font files

  • For Google Font

Add the &display=swap parameter to the end of your Google Fonts URL:

<link href=”https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap” rel=”stylesheet”>

Note: font-display: swap method may not work on all browsers; you may need to follow browser and stack specific guide to solve the FOIT issue.

32. Keep request counts low and transfer sizes small

For every HTTP request that the browser sends, the server opens the connection, handshake, and sends data back. This happens again for the next request; each element and unique domain needs a separate request. Modern web servers manage connection better, but if there is a latency, then performance is degraded multifold.

The same is with download size; the larger the files to download, the longer it will load the page. In addition, if some of those larger downloads block the render, then page load performance degrades further.

PageSpeed shows how many requests are made and how much data is transferred. It is more of informational data than suggestions.

Keep request counts low and transfer sizes small
web.dev

How to reduce resource counts and transfer sizes?

There is no one-size-fits-all solution to reduce resource counts and transfer sizes; a few options are as follows.

To minimize the number of requests

  • Avoid multiple page redirects.
  • Combine images using CSS sprites.
  • Remove unwanted third-party scripts.

To reduce download sizes.

  • Compress your text resources.
  • Minify your CSS and JavaScript.
  • Properly size and compress images.

33. Lazy load third-party resources with facades

In simpler words, it means delaying the loading of third-party embeds and replacing them with a placeholder/thumbnail or a facade. The facade should be a static element like a small thumbnail. You save time by not downloading third-party files in the initial phase of page load.

The most common third-party scripts eligible for these are dynamic ads, videos, social media widgets, and chat apps. These can be lazy-loaded with interaction (hover, onClick, etc.).

Pagespeed detects third-party scripts and compares them with data on Third-Party Web. Audit fails if resources belong to one of these third-party embeds and show the following suggestions.

Lazy load third-party resources with facades

How to defer third-party scripts with a facade?

Load a page with static elements that look similar to the embedded object rather than embedding it directly in HTML. Then, on mouseover, pre-connect to the third-party resource and on click download and replace the facade with the actual embed.

Recommended Facades

YouTube embedded player

Vimeo embedded player

Live chat

34. Minify CSS

CSS is considered render-blocking; browsers don’t render content until CSS is downloaded, parsed, and executed. Therefore, bigger and complicated CSS can delay the page load performance.

CSS file size can be reduced, a.k.a minified, by removing comments, white spaces, and redundant code.

PageSpeed shows a list of all unminified CSS files with potential saving in KiB.

Minify CSS

How to minify CSS?

CSS minification should be part of your development cycle. But it can be managed with plugins post-development too.

  • Online Tools

There are several free online tools like MinifyCode, which can be used to minify CSS, HTML, and JavaScript.

  • Build Tools

Advanced users can use build tools like gulp or grunt to minify CSS files.

  • Using CDN

Your server can have a normal CSS file, but CDN minifies it; this minified version is served to browsers.

  • With Plugin

WordPress has dozens of plugins that can minimize the CSS after the site is live.

35. Minify JavaScript

Like CSS, minification of Javascript offers similar benefits. Therefore, similar tools and strategies are used for JavaScript minification.

36. Minimize main-thread work

The main thread on the render process turns a code into the web page by parsing HTML, building DOM, Parsing CSS, and execute JavaScript. The main thread also processes user inputs; if the main thread is busy, then the web page may not respond to user interactions, thus giving a bad user experience.

PageSped flags pages that keep the main thread busy for more than 4 seconds and shows the following suggestions.

Minimize main-thread work

It shows a breakdown of where the CPU is spending time while loading the page.

How to minimize main thread work?

There is no easy solution to minimize thread work. It requires complete website/web app knowledge and development expertise. It is not in the scope of this article to cover solutions in detail. Instead, here are some useful links based on the category of the suggestion.

Script evaluation

Style and layout

Rendering

Parsing HTML and CSS

Script parsing and compilation

Garbage collection

37. Preconnect to required origins

Slower networks, multiple redirects, longer DNS lookups can slow down page load while requesting third-party resources. With preconnect, you can establish an early connection with third-party origin. This helps the browser to spend less time waiting and can receive responses sooner.

Use preconnnect wisely

  • Effective only for third-party resources, not for the request on the host server.
  • Browsers close any connection if it’s not used within 10 seconds.
  • Use preconnect critical third party resources and dns-prefetch for other non-critical requests ( reduces DNS lookup time)

How to preconnect to required origins?

<link rel=”preconnect” href=”https://third-party-example.com”>

for non-critical resources use -prefetch

<link rel=”dns-prefetch” href=”https://third-party-example.com”>

38. Preload key requests

Browser downloads and parses HTML to retrieve resources needed for the page. Some resources might load late because those are at the end in the order. For example, sometimes fonts and images could reference CSS or JSON; scripts call other JavaScripts internally. This results in an extended critical request chain, plus it might cause a cumulative layout shift. With preload, you can manage the order of resources to load.

PageSpeed flags the third level of requests and suggests improvements in ms.

Preload key requests

How to declare preload links?

<head>
  ...
  <link rel="preload" href="styles.css" as="style">
  <link rel="preload" href="ui.js" as="script">
  ...
</head>

39. Preload Largest Contentful Paint image

LCP means the largest content painted by the browser; most of the time, it’s an image for the background, slider, or hero. Often these elements are far down in the request chain. So by preloading LCP image page appear visually complete sooner than page load.

GTmetrix

How to preload Largest Contentful Paint image?

Add the following code to the <head> of your HTML:

<link rel="preload" href="/path/to/image.jpg" as="image">

You can also use <link rel=”preload”> with responsive images as follows:

<link rel="preload" as="image" href="/path/to/image.jpg"
  imagesrcset="image_400px.jpg 400w, image_800px.jpg 800w, image_1600px.jpg 1600w"
  imagesizes="50vw"/>

40. Properly size images

It is one of the most common issues which affects page load performance. Images of bigger resolution are added, which are intended for smaller space. However, bigger file sizes add more data to download, plus the browser needs to do more work to adjust image size as per CSS. Furthermore, this may cause the cumulative layout shift too.

How to size images properly?

  • Manually resize images.
  • Use srcset HTML tag to tell the browser about image variations and instruct it to use specific images based on the situation.
  • Use image CDN.
  • Use vector images over raster images.

41. Reduce initial server response time

When you open a page, the browser sends a request to the server; the server works on the request, queries the database, processes backend code, and builds an HTML page. Once done server sends back generated HTML to your browser.

Server response time, also known as Time to First Byte (TTFB), is one of the major back-end speed optimization points. A slow TTFB affects the frontend performance as the browser waits longer to receive files to download, parse and paint on the browser.

How to improve server response times?

Poorly coded application logic, database performance, server resources, poor server architecture causes slower response times.

Optimize application code

It is a complex solution; only an experienced developer can work on this. A developer needs to know complete architecture, working, and coding expertise to work on this.

Server-side caching

You can use server-side caching and optimization plugins like W3 Total Cache, WP Super Cache, WP Rocket, etc.

Add Server CPU and/or memory.

If you analyze that resource crunch is the problem, then you can add more CPU and/or memory as per the diagnosis.

42. Reduce JavaScript execution time

Javascript executes on the main thread, and while it is executing, it blocks other tasks. Therefore, reducing JS execution time means reducing time spent on parsing, compiling, and execution.

Depending on stages of JS execution, it can prevent elements from being painted, delay the rendering process, or temporarily block user interactivity. By reducing JS execution time, these cascading effects can be averted.

PageSpeed warns if JS execution takes more than 2 seconds and fails when it takes more than 3.5 seconds.

Reduce JavaScript execution time

How to speed up JavaScript execution?

43. Reduce the impact of third-party code

Most common third party resource that affects page load performance are ads, embeds, chatbots, and analytics codes served from a different domain than your host. Scripts from these external resources also execute on the main thread, which blocks other resources.

External resources affect performance due to slow DNS lookups, slower response times, and other issues. PageSpeed flags external code that blocks the main thread for 250ms or longer.

Reduce the impact of third-party code

How to reduce the impact of third-party code?

Keep whats needed

Try to use third-party scripts that are absolutely required for the functionality (e.g., analytics code, advertising tracking codes/pixels, etc.). Remove unused external resources.

Load third-party JavaScripts efficiently.

Defer or async non-critical JS. Establish early access for necessary resources with preconnect and others prefetch DNS with dns-prefetch.

Host third-party resources on your host

You can host third-party scripts on your server to reduce DNS lookups and round trips.

44. Reduce unused CSS

CSS is a render block resource; it delays First Paint until the browser finishes the parsing and execution.

CSS rules that are used to render below-the-fold content or other pages can be labeled as non-critical for the loading performance of that page. The older website may have a dead/deprecated CSS code.

By reducing the amount of unused CSS, you can reduce browser execution time and bandwidth consumed.

Reduce unused CSS

The Coverage tab of Chrome tools is used to identify Unused CSS.

How to reduce unused CSS?

  • Inline the critical CSS required for first paint inside <style> block. Add the rest of the styles asynchronously using the preload link.

The process of extracting and inlining “Above the Fold” CSS can be automated using the Critical tool.

  • Manually analyze dead CSS and remove it.

45. Reduce unused JavaScript

Like unused CSS, unused Javascript also has similar effects and solutions.

46. Remove duplicate modules in JavaScript bundles

Generally, JavaScript bundles are built by importing code from different libraries, packages, and dependencies. Unfortunately, this often results in duplicate modules from multiple sources.

This adds extra code to be downloaded, parsed, and executed; this increased waiting, download, and execution time.

There is no one-time or direct solution for this; you need to incorporate the best web development standards and workflows. Tools like webpack-stats-duplicates help developers to identify duplicate modules.

47. Replace large JavaScript libraries with smaller alternatives

Note: This audit was moved to experimental status in Lighthouse 6.4.0.

Smaller alternative libraries help optimize JS payload, speed up delivery without losing functionality.

You need to select optimal libraries at the initial stages of development. Tools like Bundle Phobia helps find alternate JavaScript packages.

48. Serve images in next-gen formats

PNG and JPEG time-tested homage formats and supported almost all browsers on the planet. But new image formats like AVIF, WebP, JPEG 2000, JPEGXR offers better compression and image processing. But these new image formats may not have universal browser support.

Serve images in next-gen formats

AVIF (AV1 Image Format) is the newest image format on the table and backing by big companies like Google and Netflix. AVIF compression is better than WebP. WebP can compress JPEG images by 50%, AVIF can compress them by 70%. You can use online AVIF converter tools.

How to Use AVIF on Your Website?

The safest way to use .avif on your website is with the <picture> element to avoid browser issues.

See the procedures to use the AVIF image below:

<picture>
<!-- use AVIF image if the browser supports it -->
<source type="image/avif" srcset="image.avif">
<!-- in case the browser does not support AVIF -->
<img alt="A Fallback image" src="image.jpg">
</picture>

49. Serve static assets with an efficient cache policy

On Every page request browser downloads all resources, e.g., HTML, CSS, Images, JavaScript. Browser Caching stores static assets ( CSS, JavaScript, images) locally. Instead of downloading again from the server for the next visit, the browser gets these locally stored resources. This speeds up the second and later visits. But enabling caching does not improve the first load on the webpage, as for the first time, browsers download all resources from the server.

How to serve static assets with an efficient cache policy?

For Apache servers

Use the following code in your .htaccess file.

<IfModule mod_expires.c>
  ExpiresActive On

 # Images
  ExpiresByType image/jpeg "access plus 1 year"
  ExpiresByType image/gif "access plus 1 year"
  ExpiresByType image/png "access plus 1 year"
  ExpiresByType image/webp "access plus 1 year"
  ExpiresByType image/svg+xml "access plus 1 year"
  ExpiresByType image/x-icon "access plus 1 year"

  # Video
  ExpiresByType video/webm "access plus 1 year"
  ExpiresByType video/mp4 "access plus 1 year"
  ExpiresByType video/mpeg "access plus 1 year"

  # Fonts
  ExpiresByType font/ttf "access plus 1 year"
  ExpiresByType font/otf "access plus 1 year"
  ExpiresByType font/woff "access plus 1 year"
  ExpiresByType font/woff2 "access plus 1 year"
  ExpiresByType application/font-woff "access plus 1 year"

  # CSS, JavaScript
  ExpiresByType text/css "access plus 1 month"
  ExpiresByType text/javascript "access plus 1 month"
  ExpiresByType application/javascript "access plus 1 month"

  # Others
  ExpiresByType application/pdf "access plus 1 month"
  ExpiresByType image/vnd.microsoft.icon "access plus 1 year"
</IfModule>

50. Use a Content Delivery Network (CDN)

Note: This is not LightHouse/PageSpeed audit; it is a custom GTmetrix audit. We are adding it here because CDN does help in improving page load performance.

A CDN (Content Delivery Network) is a collection of interconnected servers spread across the world. Each CDN node is located at strategic geographic locations—these nodes stores your website content like Images, CSS, JS, etc.

Cloudflare

Note: Dynamically generated content, pages where content changes frequently should not be cached (e.g., Login, Reset Password, Pricing, Carts, etc.)

In WordPress, HTML is generated dynamically, so it is not the right candidate to cache it on CDNs.

Here are some of the popular CDN providers

  1. Cloudflare
  2. KeyCDN
  3. StackPath
  4. AWS Cloudfront
  5. Google Cloud CDN
  6. Rackspace
  7. Incapsula

51. Use explicit width and height on image elements

Images, videos, embed without explicit width and height parameters cause large layout shifts. When width and height parameter is provided, browser reserved that exact space for elements. So, when the image/element get downloaded browser does not need to adjust the space for it to fit in.

<img src=”cat.jpg” width=”600″ height=”300″ alt=”Brown Cat on Tress”>

52. Use HTTP/2 for all resources

HTTP/2 offers greater benefits over HTTP/1.1. It handles more parallel requests and has a lower protocol overhead. This helps in speeding up the page load.

How to HTTP/2 support Apache (Bitnami image)?

  • Add the following lines in the default Apache virtual host configuration file at /opt/bitnami/apache2/conf/bitnami/bitnami.conf, inside the default VirtualHost directives, so that it looks like this:
  • <VirtualHost _default_:80> ... Protocols h2 h2c http/1.1 H2Direct on </VirtualHost> ... <VirtualHost _default_:443> ... Protocols h2 h2c http/1.1 H2Direct on </VirtualHost> Repeat the above change for any other virtual hosts you may have defined.
  • After modifying the Apache configuration files, restart Apache to apply the changes.sudo /opt/bitnami/ctlscript.sh restart apache


53. Use passive listeners to improve scrolling performance

Browsers like chrome by default blocks Scroll, Wheel events until JavaScript finishes executions. The JS execution page either does not respond to user input or causes a scroll jank where the page stutters on user input.

To fix this, add a passive: true flag to every event listener flagged. For example,

document.addEventListener('touchstart', onTouchStart, {passive: true});

54. Use video formats for animated content

Most developers use GIFs for animations, which are generally huge files that affect the download speed and delivery of animated content. MPEG4 or WebM should be used for animation content

You can use an online converter like ezgif.com or cross-platform command-line tools like FFmpeg to convert GIFs to MPEG4s.

55. User Timing marks and measures

JavaScripts are one of the main culprits for sub-optimal webpage load performance. To find the solution, you should know where the issue is and how it contributes to the bigger problems. User Timing API helps you in measuring Javascript performance; it gives you JavaScript execution timings.

This is not a direct performance metric; rather, it’s a helpful tool to improve page load speed. It is an advanced topic and out of the scope of this article. You find the details here.

About Author

Sorry, Comments are closed!