Optimize WordPress Core Web Vitals

 |  by

What is Google Core Web Vitals?

A paragraph on TechCrunch described it briefly:

One year. That’s how long Google gave developers to start implementing required changes to improve user experience.
In early May 2020, Google published a modest post on one of its developer blogs introducing Core Web Vitals — a set of metrics that will result in major changes to the way websites are ranked by the search engine.
In May 2021, Google will officially add those Core Web Vitals to the various other “page experience” signals it analyzes when deciding how to rank websites.

TechCrunch

In simpler words, Google wants our site to load fast(er) in order to ensure that our visitors have a good first impression of user experience, by trying to quantify it using these 3 metrics.

lcp - largest contentful paint
fid - first input delay
cls - cumulative layout shift
  • Largest Contentful Paint (LCP)
    This measures loading performance on the elements that are visible in the viewport (above the fold area). Many website designs have different content that is visible in the viewport between the desktop and the mobile version. So we really need to be aware of this. The best practice is to care more for the mobile version. 
  • First Input Delay (FID)
    This measures interactivity. It calculates how long our visitors can actually interact with our page after the browser rendering process.
  • Cumulative Layout Shift (CLS)
    This measures visual stability; the amount of page layout shifts during the loading phase.

Should we worry about google statements and these metrics? Not really.
Should we try to stay ahead of the curve, analyze our site and try to make improvements? Yes, definitely!

What google aims at the end is to give each visitor a good first impression on user experience, each time they visit a site.

If it is a company profile website, they want the visitors to be able to quickly see and learn about our business profile. If it’s a shop / online store website, they want the visitors to be able to quickly enter our site, browse, and buy the products. If it’s a blog, they want visitors to be able to quickly access the blog and read articles that interest them.

Those are things that we should agree on, right?

DO: Use google tools to check our site core web vitals. Identify the opportunities to increase our site speed by examining the suggestions given.

DON’T: Get obsessed by the score.

Update: Google just annaunced that they postponed the implementation date of Core Web Vitals as one of “page experience” signals to the end of August, 2021.

What Matters Most?

It’s the Above the fold area.

Basically, all three of the Core Web Vitals metrics (LCP, FID, and CLS) measures and quantify its scores based on everything that is visible in above the fold area, and what produced them in the backgrounds.

So this should be our major topic.

  • Above the Fold Area
    It refers to the portion of a webpage that is visible at the first time without scrolling. Basically it’s everything that the website shows on the first screen / view port when visited.
  • Below The Fold Area
    It’s everything below the above the fold area.
above-and-below-the-fold-s
source: web.dev

How to Optimize Our Website Core Web Vitals: A Definitive Guide

The goal is to reduce bloats in general, and makes the above the fold area loads quick with minimum layout shift.

ThinkWeb

ThinkWeb’s 4 basic principles to optimize page speed:

  • Reduce bloats, remove unnecessary assets.
  • Preload important assets that are producing the above the fold contents if necessary. 
  • Delay static assets (or lazy load, in terms of images) as much as possible.
  • If delaying gives bad results, preload them.
These are 10 proven steps and tutorials to optimize our website’s Core Web Vitals in order to stay on top of the (SEO) competition.
  1. Inline Critical CSS
    Critical CSS, in our definition, is:
    1. A group of styles that contain classes of the critical contents above the fold, or
    2. CSS that is used to style the above the fold contents.

    Creating / extracting and inlining our page’s critical styles in the <head> section will make the browser styles and layouts our above the fold contents in much faster time.
    It will also improve our page’s FCP, FID, Speed Index, and TTFB, and also reduce our CLS (to zero, if we did it right).
    And by doing it, we can set the rest of the style in the CSS files to load asynchronously.
    <style id="inlined-critical-css-example">
    html, body {
      max-width: 100vw;
      overflow-x: hidden;
      background-color: #171717;
      font-weight: 400;
      font-size: max(16.5px,min(17px,(100vw - 100vmin)))
    }
    html {
      -webkit-text-size-adjust: 100%;
      -ms-text-size-adjust: 100%;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      box-sizing: border-box;
    }
    :root, html, body, button, input, select, textarea {
      font-family: thinkweb,Tahoma,Geneva,sans-serif;
    }
    ...
    </style>

    While we can do this manually by inspecting the elements style of the above the fold contents and compile them in to one set of an inlined style, we can also use online critical css generators like Sitelocity and Pegasaas to create it automatically.
    This is why this should be the first step (before removing any unused CSS, or any other steps that we will explain later).
    The way those online critical CSS generators work are extracting our critical CSS after scanning our html and all of our CSS files. So the possibilities to have a fully functional critical CSS are better than if we create it before removing any unused CSS files. We can always purify it or remove the unused CSS after.
    Remember, the goal is to make our above the fold contents load fast without any layout shifts. Inlining styles in the <head> section indeed eliminates the needs to make additional requests to fetch the styles that are used to style our website contents. But don’t overuse it by inlining all of our style.
    The downside of inlining all of our style in the <head> section are:
    1. Our html size will become large and make the browser rendering process slower, especially if the page is large and heavy.
    2. Our style won’t be cached by the browser, so it would only be good for achieving the scores, but not for our visitors benefits and overall user experiences.

    So the best practice is to just inline the critical styles, and leave the rest of the css files untouched, purified, and/or load them asynchronously.
  2. Check Our Loaded Assets
    Deactivate all of our performance plugin (eg: cache plugin, etc), and check the loaded assets in GTmetrix waterfall tab.
    gtmetrix waterfall
    Using GTmetrix’s waterfall tab is the easiest way to check what assets are loaded by our page. It gives us a list of assets that our page is requesting, that are comfortable to read. They also provide sub-tabs so we can filter the assets based on its type (eg: fonts, css, js, image, etc).
    All of those requests are render blocking by nature. We need to reduce them by identifying which one or two that should be removed.
    The key to optimize a page speed is to reduce bloats. To do that, we should minimize the request and the total file size, and only load things that are really necessary.
    Notes: your waterfall results may have more requests from ours.
  3. Identify Our Unused Assets
    We can use chrome dev tools > show coverage for this. It was developed by Google to check how many unused bytes in a page for each of our CSS and JavaScript.
    check unused css and JavaScript
    Unused bytes are the size of the unused codes in our CSS and/or JavaScript. As we can see in the image above, the red bar shows the unused bytes of each CSS and JavaScript.
    The more plugins or features we have, the longer list we get. And usually, more unused bytes.
  4. How to Handle Unused CSS
    (Unused) CSS are relatively easy to handle. These are the 2 best way to handle it.
    • Remove:
      If the unused bytes shows more than 90%, and it’s not being used in above the fold area, it’s considerably safe to be removed. Just try and check. Remove them first. If the layout breaks, undo and try the next methods below.
    • Purify:
      If the unused bytes shows below 90%, remove the css file, create new css file with the purified version. To purify css, we can use purifycss.online and/or uncss-online.com.
  5. How to Handle Unused JavaScript
    Unlike CSS, we can’t easily purify JavaScript. So the options are:
    • Remove:
      If the unused bytes shows more than 90%, and it’s not being used in above the fold area, it’s considerably safe to be removed. Like CSS, just try and check. Remove them first. If the layout breaks, undo and try the next methods below.
    • Delay:
      We can block and delay JavaScripts rendering time after any user interactions. Check out Flying Script (free) and WP Rocket (paid) delay JS feature. This delay JS method is simple but useful. Especially for external or 3rd party scripts like Gtag, FB pixels, Cookie/GDPR Notice, etc. We just need to insert the keyword of the JavaScript that we want to delay (it can be inlined JavaScript or a JavaScript files), and the plugins will do the job. 
  6. How to Remove Assets on WordPress
    Removing assets in WordPress is actually relatively easy. Especially if our theme, or the plugins we use, don’t give much or too many dependencies from its one assets to another.
    1. First, Identify the handler
      identify css and java script handler in html view source
      Finding the assets handler in WordPress is not a difficult task. If we take a look at our website html source, we can see some lines of requests for CSS and JS like in the image above. The ID is the handler, minus the “-css” (for CSS files) and “-js” (for JS files) suffix.
    2. Remove the Unused Assets with WordPress Dequeue & Deregister Function
      There’s a popular plugin named Asset CleanUp to do this job. But we prefer not to use it. It’s kinda overkill and more complicated to use. We can do it manually, without plugin.
      How to remove wordpress assets (CSS/JS) manually without plugin in any page or certain page:
      function tw_unload_files() {

      wp_dequeue_style ( 'optim-style' ); // *_style is for css
      wp_dequeue_script ( 'jquery-core' ); // *_script is for JavaScript

      }
      add_action( 'wp_enqueue_scripts', 'tw_unload_files', 100 );
      The above code is an example if we want to remove the “optim.css” file and “jquery.min.js” file from our page load.
      Put this code in our child theme’s function.php or any place that we use to put custom code snippets. Copy & paste the code, and simply change the handler names.
      The code above applied site wide, on all of our pages and posts. If we need to put some conditionals, we just need to add the conditions.
      function tw_unload_files() {

      if ( is_front_page() ) {
      wp_dequeue_style ( 'optim-style' );
      wp_dequeue_script ( 'jquery-core' );
      }

      }
      add_action( 'wp_enqueue_scripts', 'tw_unload_files', 100 );
      The above code applied the removal for front page / homepage only. If we need to remove the assets from the front page and/or any other page, we can use the page id and/or post-type for that.
      function tw_unload_files() {

      if ( is_front_page() || is_page([page-id]) || is_single() || is_product() ) {
      wp_dequeue_style ( 'optim-style' );
      wp_dequeue_script ( 'jquery-core' );
      }

      }
      add_action( 'wp_enqueue_scripts', 'tw_unload_files', 100 );

      Learn more about WordPress Conditional Tags.
      Easy, right? Mastering the enqueue/dequeue and conditional functions will give us a clear path to be a Speed Jedi. It will make any page optimization job easy.
      Note: the “wp_dequeue” prefix works for assets that loaded with wp_enqueue functions. If our plugin use wp_register functions (like elementor usually did), we should use “wp_deregister” prefix. Just try them both and see which one is working.
      If it’s still seems too difficult for you, you can use Asset CleanUp (we suggest that you use it like its name, to clean assets only, as we find the other features are overlapping the cache plugin features.) or any Plugin & Script Organizer to do this job.
  7. How to Handle Images
    1. Compress, Reduce, and Resize
      We should always remember that most of each website’s traffic nowadays came from mobile devices.
      So unless our website is a photography website, we don’t need to display high-resolution images. Forcing browsers to load high-resolution images is a huge waste of cost for our visitors. And it will also directly affect our scores significantly.
      Compress, reduce, and resize all of our images to the proper size is wise to increase our website speed and performance.
      Our recommendations for image file size:
      • Around 150kb, and not more than 200kb, for hero / cover images.
      • Around 40kb (or lower) to 80kb, and not more than 100kb, for other image type.
      When and How We Should Compress Them?
      The best practice is to compress our images before we upload them. Don’t use plugins to do this job, as it will create much duplicate images in our storage. We will have much more benefits if we do it manually with our desktop app or any online image compressor.
      What if we already have plenty of existing images which are still uncompressed? Just download them all, bulk compress them, and then, re-upload them.
    2. Delay Below the Fold Images
      We should delay the request of all below the fold images until our visitor needs them by implementing the lazy load image technique.
      There are 2 major popular methods for doing this.
      • Native lazy loading. It’s a browser-level image lazy-loading. It basically just add loading="lazy" attribute in our img tag. Most of modern browser already support this method. And WordPress implement this method by default since WordPress 5.5.
      • Using JavaScript. There are plenty of JavaScript libraries that are built to deferring images. Some use Intersection Observer API, and some use the JavaScript event handlers.

      Both are delaying the image requests until it’s visible in the viewport.
      Which one is better and we should use? Either option let us include lazy-loading functionality to our website. So It’s really just a matter of preference. Our visitors wouldn’t know and feel the difference. But, if our goal is to achieve better scores, in our experience, the JavaScript method could help us more.
      Please note: Don’t delay any of our above the fold images, as it will increase our Cumulative Layout Shift. Remember, everything in the above the fold area should load and appear quickly. So in most cases, the best practice is to preload them instead.
    3. Use Image Dedicated CDN
      There are two major benefits in using image dedicated CDN:
      1. To decrease our server load.
      2. Take benefits of their On-The-Fly Image Optimization feature.

      The second one is a huge deal. With On-The-Fly Image Optimization we can have our images file size reduced (compressed) automatically (on the fly) and give us a little more performance gain. Most of the Image Dedicated CDN offer this feature. Imagekit does this beautifully. And it’s free!
  8. How to Handle Fonts
    1. Text Font.
      Limit the number of fonts that we use. Use only 2 fonts maximum. Or, simply just use the web-safe-fonts collections, so we don’t have to make any additional requests for our text font.
    2. Icon Font.
      Just don’t use it. Icon font sizes are mostly huge! And we only use not more than 90% of its characters most of the time. Consider to change all of our icons to SVGs.

    If we really still have to use them:
    1. Whether it’s a text font or an icon font, the best practice is to self-host all of our fonts.
    2. Purified all of our CSS text font and icon font, and put it on our inline style (critical CSS) so the browser can read it quickly.
    3. Preload the critical font file(s) to avoid FOUT (Flash of Unstyled Text) when visitors make their first visits.
  9. Handling the Above The Fold Content Area
    1. Make It Simple
      Remember, basically all three of the Core Web Vitals metrics (LCP, FID, and CLS) measured and quantified its scores based on everything that is visible in our above the fold area, and what produced them in the backgrounds. So it would be wise if we designed our above the fold area simple.
      The best practices are:
      1. Not using sliders, carousels, or any JavaScript-driven content in the above the fold area.
      2. Not using more than 2 image in the above the fold content area. (eg: 1 image for logo, and 1 image for the hero section)
      3. Not using too many columns in the above the fold content area.
      4. Not using too many or complicated HTML structures. Reduce our DOM Elements.

      Note: We might have different content that is visible in the viewport between our desktop and mobile version. If we’re not designing our responsive design in the right way, we might get a big gap between desktop and mobile scores. It would be best if we set the hero section with minimum 100vh for the height.
    2. Make It Fast and Light
      Again, remember, the goal is to make our above the fold contents load fast without any layout shifts. So, to achieve this we should:
      1. Not combining our CSS and JavaScript. Especially if we have a large and heavy page.
      2. Preload any critical assets (eg: fonts, CSS, JS, and images) if we must.
        To preload any assets, basically we just needs to insert this in our page <head>:
        <link rel="preload" as="the-asset-type" href="the-asset-url-path">

        Here’s a few examples of how to preload image, CSS, JS, and font files:
        /* to preload image */
        <link rel="preload" as="image" href="/wp-content/uploads/optimize-core-web-vitals-s.jpg">

        /* to preload font */
        <link rel="preload" as="font" href="https://fonts.gstatic.com/s/roboto/v20/KFOmCnqEu92Fr1Mu4mxKKTU1Kg.woff2" crossorigin>
        // to preload fonts, we need to put 'crossorigin' at the of the link tag, so the browser not fetch it twice

        /* to preload JavaScript */
        <link rel="preload" as="script" href="/wp-content/themes/generatepress/assets/js/main.min.js">

        /* to preload CSS */
        <link rel="preload" as="style" href="/wp-content/themes/generatepress/assets/css/main.min.css">
        // to preload CSS files, we need to make sure the actual CSS request (link rel="stylesheet") exist, otherwise, it won't work.
      3. Delay any non critical assets (eg: CSS, JS, and images).
        We really should delay (or lazy load, in terms of images) any assets that are not critical and are used in below the fold area.
      4. Establish early connections of critical 3rd party resources.
        If we use 3rd party resource for our assets (eg: google fonts), we should add “dns prefetch” or “preconnect” in a link tag to establish early connections to the important third-party origins.
        /* to pre-connect google fonts */
        <link rel="preconnect" href="//fonts.gstatic.com">

        /* to prefetch dns of google fonts */
        <link rel="dns-prefetch" href="//fonts.gstatic.com">

        We can learn more about preconnect and dns-prefetch in this web.dev article.
        Keep in mind, use this for the critical assets only as it can backfire and slow down our page.
      5. Use full HTML Page Cache.

        When a visitor comes to your WordPress site, their browser talks to your web server which loads up WordPress – this involves PHP processing, making requests to your database, sending files back to the browser to finally be assembled into a fully formed webpage

        WP Rocket

        That’s why we need to implement HTML Page Caching, at the very least. Serving the page’s html cache version reduce those sequence by removing the PHP and requests to the database. So the browser can load the page much faster.
        Other caching methods to consider can be found also in WP Rocket’s Blog.

  10. Optimize Our Database
    Every page of a WordPress based website is dynamic; generated from information stored in databases (and/or external files). So frequently optimizing our database is a must to ensure our WordPress site’s performance.
    1. Clean our post database revisions, auto drafts, trashed posts, spam and trashed comments, unused and duplicates meta, and transients.
    2. Check and decrease our autoloads in the wp_options table.
      Open the SQL Database / phpMyAdmin and use this command:
      SELECT option_name, length(option_value) AS option_value_length FROM wp_options WHERE autoload='yes' ORDER BY option_value_length DESC LIMIT 200;

      Delete everything that we no longer use. If we’re unsure if it’s safe to delete or not, just change the autoload value to “no”. Johnny Nguyen has more comprehensive tutorials for this in his articles.

After doing all of those 10 steps to optimize our core web vitals above, we should have all of our scores turn to green in Google Page Speed Insights, or even any other performance test tools. Getting 90+ score is not a difficult task if we follow those 10 steps guidance. Remember, before doing anything, make backups first, just to be safe.

Take notes, don’t get obsessed by the scores. Don’t over optimize our page either. Optimizing WordPress Speed and Performance should be a balancing act between the effort of getting good scores and preserving features. Therefore, it should be done carefully.


Getting green score on our Core Web Vitals can be one of important factors for our search engine ranks, but creating good content should always be our focus. Google considers a number of ranking signals. So while these are important, if we don’t have a good and relevant content, we’re unlikely able to outrank our competitors.

While all of the components of page experience are important, we will prioritize pages with the best information overall, even if some aspects of page experience are subpar. A good page experience doesn’t override having great, relevant content. However, in cases where there are multiple pages that have similar content, page experience becomes much more important for visibility in Search.

Sowmya Subramanian, Director of Engineering for Search Ecosystem on Google Dev’s Blog

Need to Optimize Website Speed and Core Web Vitals? Try Our Service!

Photo of author

By

Arya Dhiratara

Co-Founder.

Leave a Comment