Tag: Optimize WordPress Database Queries

  • How To Use Cookie-Free Domains with Cloudflare in WordPress- CDN

    How To Use Cookie-Free Domains with Cloudflare in WordPress- CDN

    Seeing “Use cookie-free domains” error at GTmetrix Yslow or Pingdom for your site?

    GTmetrix report

    Why use Cookie Free Domains?

    When the browser requests a static element and sends cookies with the request, the server ignores the cookies. These cookies are unnecessary network traffic. It increases page load time. Therefore, it is better to avoid cookies for static resources like CSS, JS, Images, etc. files. This is why speed test tools such as GTMetrix and Pingdom recommend to serve the static resources from a domain that doesn’t set cookies.

    Solutions

    • Use a CDN
    • Use Cloudflare only for DNS

    #1. Use a CDN to Serve Cookie-Free Content

    As unnecessary cookies can come from various sources such as Cloudflare, Analytics, top-level domain names and so on, it’s better to completely offload static resources to a CDN unique hostname.

    • Use BunnyCDN to serve all static resources cookies-free.
    • Or, use Stackpath (Formerly known as MaxCDN), they support cookie-free domains.
    Strip all cookies with Stackpath CDN

    This method should work for site using top level (non-www) domain or www alias.

    Bonus tip: If you’re using Yoast SEO WordPress plugin, it would be best to update the image path in XML file. You can add the below snippet via Code Snippets plugin.

    function wpseo_cdn_filter( $uri ) {
    	return str_replace( 'https://example.com', 'https://example.stackpathcdn.com', $uri );
    }
    add_filter( 'wpseo_xml_sitemap_img_src', 'wpseo_cdn_filter' );

    #2. Use Cloudflare only for DNS

    Generally, you can’t serve cookie-free content while using its CDN (Reverse Proxy) services together. The way Cloudflare provide services, it must add a special cookie namely _cfduid with each HTTP request over whole domain.

    HTTP/1.1 200 OK
    Date: Thu, 26 Mar 2020 15:37:09 GMT
    Content-Type: image/vnd.microsoft.icon
    Content-Length: 0
    Connection: keep-alive
    Set-Cookie: __cfduid=d36b1934da000d3fbc11e5a8e13fccde11585237029; expires=Sat, 25-Apr-20 15:37:09 GMT; path=/; domain=.cloudflare.com; HttpOnly; SameSite=Lax; Secure
    Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
    CF-Cache-Status: HIT
    Age: 4650
    Accept-Ranges: bytes
    Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
    X-Content-Type-Options: nosniff
    Server: cloudflare
    CF-RAY: 57a1f3878d3ad597-BOM
    alt-svc: h3-27=":443"; ma=86400, h3-25=":443"; ma=86400, h3-24=":443"; ma=86400, h3-23=":443"; ma=86400

    Solution: To eliminate __cfduid cookies, keep Cloudflare in DNS only mode or switch to Enterprise Plan that allow to remove but it would be costly. Alternatively, you can use Sucuri performance and security solution which doesn’t set cookies with each request.

    #3. Switch to Static WordPress

    This blog is live example a static WordPress site. It is hosted at BunnyCDN Cloud Storage. I am huge fan of their services and amazing support.

    Key facts

    • It helps serving pages without cookies.
    • The process require deep technical understanding of CDN, Caching Policy and end result is worth it.
    • I use Cloudflare only as DNS not proxy.
    • My all pages score 90+ at PageSpeed Insight
    • I use WordPress just as CMS in backend but end user interact with HTML pages.

    By converting WordPress to HTML you can make your website faster than 99% of the world.

    How to check either my domain/subdomain cookiesless or not?

    Check at Network Tab of Chrome Developer tool or using GTmetrix.

    Final words: I have tried my best to explain this tutorial to you. If you have any questions in mind, or couldn’t understand this tutorial at any part. Please feel free to write to me at prospeedguy@gmail.com. I would be happy to reply to your queries.

  • How to avoid an excessive dom size in wordpress

    How to avoid an excessive dom size in wordpress

    If you’re reading this article, chances are you’ve run into an “Avoid an excessive DOM size” warning from Google Lighthouse.

    Part of selecting a good theme choice in WordPress is to avoid an excessive DOM size. Before you install the theme on your website, do some research on other websites that utilize it. Verify the performance of those websites with Google PageSpeed Insights.

    The loading performance of a web page is one of the factors that influence getting good SEO positioning. And this is a topic where the DOM size of a page is critical.

    When a website is assessed using page speed tools such as Google Page Speed or GTmetrix, the error ‘Avoid an excessive DOM size’ displays. If you’re unfamiliar with the word and want to learn more about it, you’ve come to the correct spot. This post will cover everything you need to know about avoiding an excessive DOM size in WordPress.

    What is the DOM?

    Your browser creates a tree structure of the objects called DOM (Document Object Model) every time it loads a web page.

    DOM is a tree diagram of objects in your HTML. It shows each HTML element such as the body or h1 with its own node.

    DOM represents the hierarchical nature of different objects which may or may not depend on each other. As mentioned earlier, it displays the webpage’s HTML structure as a tree, composed of a series of tags.

    Here’s how it works: when your web browser starts preparing a page to display it, it generates an object tree diagram of all the page elements according to its HTML structure.

    As a result, whenever it receives an HTML file, it begins by converting it into a tree-structured form called DOM or DOM tree. You can access the DOM and modify it using JavaScript.

    Here are some key terms related to DOM:

    • Nodes. Each element or tag in the DOM is called a node or leaf in the DOM tree.
    • Depth. The number of elements in a branch of a DOM is called depth.
    • Child element. The last node which doesn’t branch any further is called a child element.

    When analyzing your site through Google PageSpeed Insights you might have seen an error like “Avoid an excessive DOM size”:

    Or in GTmetrix “Reduce the number of DOM elements”:

    How DOM Size Impact Performance?

    Excessive DOM size can impact performance in different ways.

    • Higher parse and render time (FCP) – A large DOM tree and complicated style rules make a huge work for the browser. The browser has to parse the HTML, construct a render tree, etc. Every time user interacts or something in HTML changes, the browser has to compute this again.
    • Increases memory usage – Your JavaScript code might have functions to access DOM elements. A larger DOM tree causes JavaScript to use higher memory to process these. An example would be a query selector like document.querySelectorAll('img') which lists all images, commonly used by lazy loading libraries.
    • Increases TTFB – As your DOM size increases, the size of the HTML document increases (in KBs). Since more data has to be transferred over the network, this increases TTFB.

    How to avoid an excessive dom size Technically?

    For example, technically reducing DOM size is simple as:

    use:

    <ul id="navigation-main">
        etc..
    </ul>

    instead of:

    <div id="navigation-main">
        <ul>
            etc..
        </ul>
    </div>

    Basically, get rid of every possible HTML element. You can also use Flexbox or Grid to further reduce DOM size.

    But since you’re using WordPress, this isn’t gonna help you much!

    How to avoid an excessive DOM size in WordPress?

    Lazy Render below-fold contents

    You can tell the browser to lazy render the contents (or elements) if it’s not required for the above fold. It’s just like lazy loading images, but for HTML elements.

    Split large pages into multiple pages

    Do you have a page with everything you got on the site? Like services, contact forms, products, blog posts, testimonials, etc?

    Try to split them into multiple pages and link to them from the header/navbar.

    Lazy load and Paginate everything possible

    Lazy load every possible element. Some examples could be:

    • Lazy load YouTube videos – use WP YouTube Lyte or Lazy Load by WP Rocket.
    • Limit number of blog posts/products per page – I usually try to keep a maximum of 10 blog posts per page and paginate rest of them.
    • Lazy load blog posts/products – Add “load more” button or infinite scroll to load more blog posts or products.
    • Lazy load comments – I lazy load comments section using Disqus Conditional Load since I use Disqus. If you’re using native comments, use plugins like Lazy Load for Comments.
    • Paginate comments – If you have hundreds of comments, this can also affect DOM size. Paginate comments by going to Settings -> Discussion -> Break comments into pages.
    • Limit related posts count – Try to limit the related posts count to 3 or 4.

    Note: Lazy loading images won’t reduce DOM size

    Don’t hide unwanted elements using CSS

    Sometimes you might need to remove elements injected by the theme/builder. For example, add to cart button in product pages, rating button, author info, published date, etc.

    A quick solution is to hide them using CSS:

    .cart-button {
      display:none;
    }

    Even though this solution looks easy, you’re serving unwanted code to users (which includes both HTML markup and CSS styles).

    Check your theme/plugin settings to see if there is an option to remove it. Otherwise, find the respective PHP code and remove/comment on them.

    Use well-coded themes and page builders

    A good theme has a major role in DOM size. Use well-coded themes like GeneratePress or Astra.

    Page builders also inject too many divs. Use builders like Oxygen that doesn’t inject unwanted divs and have more control over the HTML structure.

    If you’re new to Oxygen, watch Building a Website in Oxygen from Scratch.

    Conclusion

    There might be more plugins or theme settings that inject too many divs. An example can be “mega menu” plugins like UberMenu.

    Sometimes these are crucial for your website’s user experience. But sometimes these are never used by users.

    Maybe your footer links are never clicked because most of the visitors are only scrolling up to 75%.

    Use tools like HotJar or Google Analytics events to see what visitors are actually using and not using. Analyze, measure, and iterate.

    Hope this helps! 🙂


    WordPress Speed Optimization Service

  • 9 Tips to Improve First Contentful Paint in WordPress- FCP

    9 Tips to Improve First Contentful Paint in WordPress- FCP

    In early 2019, Google announced that they would evaluate a website’s speed ranking by focusing on two performance metrics: First Contentful Paint (FCP) and First Input Delay (FID).

    Over time, the performance scenario has evolved. For instance, Google announced the three Core Web Vitals: Largest Contentful Paint (LCP), Cumulative Layout Shift (CLS), and First Input Delay (FID).

    Nonetheless, the First Contentful Paint metric has continued to play an important role as a Lighthouse (and user experience) metric. It accounts for 10% of the overall performance score.

    Your website may load under 2 seconds in a speed test, but if that’s not the case for a majority of your audience, then Google will still penalize you.

    In this article, you’ll learn what’s FCP and why it’s important. Next, we’ll move on to various ways you can improve FCP on your WordPress site.

    Sounds exciting? Let’s dive in!

    What is First Contentful Paint (FCP)?

    First Contentful Paint (FCP) is a user-centric metric for measuring perceived page load speed. FCP measures how users perceive the performance of a website, rather than what a speed test tool measures.

    First Contentful Paint differs from First Paint, which is a point in the page load timeline where any type of render is detected on the browser. On the other hand, FCP requires some content to be rendered. This content could be text, images (including background images, logos), or non-white <canvas> elements.

    First Contentful Paint also differs from the Largest Contentful Pain (LCP), one of the Core Web Vitals measuring how long it takes for the largest element to become visible in the viewport.

    To keep it simple, you can think of FCP as the time it takes for the user to see any content on their browser. Thus, a fast FCP reassures the user that something is happening and keeps them glued to the site.

    Google recently made an announcement that they’re ranking websites based on FCP and FID.

    They categorize websites into Slow, Moderate and Fast

    This is now visible in Google Search Console‘s ‘Speed’ menu.

    This is also visible in Google PageSpeed Insights as ‘Field Data’.

    “But my website loads in 2s” Why does this matter?

    The Field Data is the data collected from the Chrome User Experience Report (Crux). Chrome collects data from real users.

    Your testing tools might say your website loads in 2s or less. But your audience might be from different locations, with different devices and network speed.

    Field Data tells the actual speed that your users are experiencing.

    So if you’re trying to figure out how to reduce FCP, here are some tips:

    1. Reduce TTFB

    FCP = TTFB + render time.

    So you’ve to reduce TTFB to reduce FCP.

    There are several techniques to reduce TTFB in WordPress. The easiest one is to use a good cache plugin like WP Rocket and a good hosting provider like Cloudways.

    2. Remove Render-blocking resources

    Once the browser receives the HTML content, it may have to download extra resources in order to start rendering.

    They’re usually CSS and JavaScript.

    For JavaScript, you’ve to add a defer attribute to the script tag. The defer attribute tells the browser to only execute the script file once the HTML document has been fully parsed.

    For CSS, we’ve to load them at the bottom, asynchronously.

    Almost all cache plugins can do both. What I usually recommend is WP Rocket since it can generate critical CSS too.

    Generate Critical CSS

    When you load CSS asynchronously, the browser doesn’t have the necessary styles required. This will create Flash of Unstyled Content of FOUC.

    To prevent this, we’ve to generate Critical CSS.

    Critical CSS is the CSS that is required to render the above fold contents. It’s inlined in the HTML so that no resources need to be downloaded and the browser can immediately render the content.

    3. Use well-coded themes and page builders

    A good theme has a major role in reducing FCP. Use well-coded themes like GeneratePress or Astra.

    Page builders also inject too many divs and unwanted CSS. Use builders like Oxygen that doesn’t inject unwanted divs and has more control over everything.

    If you’re new to Oxygen, watch Building a Website in Oxygen from Scratch.

    4. Avoid JS dependent elements in Above Fold

    Anything that requires JavaScript to be executed to render can harm First Contentful Paint.

    So as a thumb rule, avoid elements that require JavaScript to render in the above fold, like these:

    • Sliders like Revolution slider
    • Google Ads
    • Mega Menu plugins
    • Animations

    5. Preload Pages in the Background

    By preloading pages in the background, whenever a user navigates to a page, the page is loaded instantly without any delay.

    Link prefetching is a browser mechanism, which utilizes browser idle time to download or prefetch documents that the user might visit in the near future.

    Mozilla Docs

    Note that this will not help for the initial page load, only for the inner pages.

    The code looks like this:

    <link rel=”prefetch” href=”URL_TO_PAGE”>

    6. Exclude ‘Above Fold’ Images from Lazy Loading

    Lazy loading usually requires JavaScript to be executed before displaying images. This can delay rendering images in the above fold.

    Always exclude images in the above fold from lazy loading. Most of the lazy loading plugins have this feature.

    7. Inline ‘Critical’ Images

    Inlining images mean the browser doesn’t have to make another HTTP request to download the image. The content of the image is already inside the HTML.

    A normal image in HTML:

    <img src=”https://yout-site.com/logo.png”/>

    A base64 image in HTML (inlined):

    <img src=”data:image/png;base64,…[content]…”/>

    8. Reduce DOM Size

    When your browser receives an HTML document, it has to be converted to a tree-like structure which is used for rendering and painting with the help of CSS and JavaScript.

    This ‘tree’ like structure is called DOM or Document Object Model.

    The more elements you add into a page, render time and First Contentful Paint increases.

    9. Ensure Text Remains Visible during webfont load

    You may have seen an error like this in Google PageSpeed Insights:

    Font files are usually added in the CSS files.

    For a browser to get the fonts ready, it has to parse HTML, download CSS files, parse them, and download fonts files.

    Until these all are done, the text is invisible! Also called Flash of Invisible Text (FOIT).

    You can fix this by adding a display:swap to CSS (@font-face). This tells the browser to use a default font until the actual one is downloaded.

    Conclusion

    As Google has started to put more focus on site speed, improving FCP is no longer a ‘good to have’, it’s a ‘necessity’.

    Not just Google, FCP and FMP are the metrics which says when a site is ‘visible’ to the user. Measuring fully loaded time is not always enough.

  • How To Speed Up & Optimize WordPress database connection

    Let’s Optimize WordPress database connection

    In this post, we’re going to break down and share how we optimize the WordPress database connection and database queries when working on site speed.
    A slow WordPress database connection or slow queries will typically manifest in areas in WordPress that aren’t cached like the WordPress backend, checkout pages in WooCommerce, or membership pages on a membership site.

    How To Speed Up & Optimize WordPress Database Queries

    There’s no magic when it comes to website speed optimization and speeding up the database end of WordPress is the same. Ultimately, the way in which you can speed up WordPress database connection & queries could be summarized as:

    1. Use better hosting;
    2. Use object caching powered by Redis or Memcached (memory based database caching);
    3. Reduce the load on the site and database;
    4. Configure the database in a best practices fashion.

    How to Speed Up WordPress Database Connection & Queries

    The recommendations below can be a bit technical, so if you have a question or need anything clarified, please post in the comments.

    1. Use a Good Host That Ideally Has Memcached or Redis Caching
      Having a high quality, reliable hosting provider that supports Memcached or Redis caching is of crucial importance. Memcached and Redis are types of memory caches that can be used for Object Caching – basically WordPress database caching.

    Redis is probably faster in most cases but Memcached is generally more widely available. These are applications installed on the server or hosting itself.

    How To Speed Up & Optimize WordPress Database Queries 2

    If you have a VPS that you’re in control of you should be able to install one of these apps on it.
    If you have a site that is heavy on database queries it’s worth looking at a host with object caching capability. Here’s three we regularly recommend that check this box:

    Siteground – Siteground is a solid mid-range host and they support Memcached and have a tutorial on how to configure it.
    Cloudways – has its VPS servers located in more than 60 places worldwide. These guys offer truly affordable hosting plans starting at $10/month. Cloudways supports both Memcached and Redis.
    *Kinsta – is a managed WordPress host and offers Redis as an addon option.

    1. Use Object Caching
      Object caching is a type of database caching that can dramatically speed up sites that have database heavy operations. Woocommerce checkout and cart operations, order management on the backend and almost everything that happens behind the logon on a membership site are all database heavy operations that will benefit from Object Caching.

    The object cache sits in front of the database and can answer previous database queries (if in the cache) without talking to the database.

    How To Speed Up & Optimize WordPress Database Queries 3

    Your host will need to support Redis or Memcached in order to use object caching and we typically use the Redis Object Cache plugin from Till Kruss inside WordPress to power the caching.

    Broadly, the steps to get this up and running are:

    Install Redis or Memcached or check with your host whether they support it;
    Add a cache salt key in wpconfig.php (important because without this, caches may jump between sites);
    Install and enable the Redis Object Cache plugin.

    1. Use the Highest Version of PHP the Site Supports
      PHP is the programming language WordPress is built on. New versions of PHP get released regularly (every 6-12 months), and each version is typically 10-30% faster than the previous version.

    Using the highest version of PHP that your site supports can dramatically speed up database-related operations.

    1. Reduce the Load by Using Page Caching
      You pretty much can’t run a WordPress site without Page Caching. With Page Caching in place, pages are pre-built before the visitor hits the website, which is a great way to speed up WordPress data queries.

    All the PHP processing and database lookups required to generate the HTML file are all done in advance and stored in the page cache. When the visitor hits the website the server provides the HTML file immediately so the user experiences a faster site and the load on the server is dramatically reduced. Typically it’ll take 1-4 seconds to generate a page from scratch whereas a cached page is available in a few hundred milliseconds (0.2-0.5 seconds)

    How To Speed Up & Optimize WordPress Database Queries 4

    WP Rocket is one of the best caching plugins on the market. It includes lots of prominent features, so it stands out as the plugin we highly recommend to everyone who wants to speed up WordPress data queries and improve their website’s performance.

    • 5. Reduce the Load by Using Cloudflare CDN

    Even if you are using a low-quality host, Cloudflare can greatly decrease your site’s load times even on the free plan.

    Cloudflare offers several speed optimizations and speed benefits such as:

    How To Speed Up & Optimize WordPress Database Queries 5

    Fast DNS (Domain Name System) hosting – Cloudflare is typically one of the fastest DNS hosts in the world, see https://dnsperf.com for real time rankings
    Security & Firewall even on the free plan Cloudflare can filter a lot of the garbage traffic hitting your site. There’s some custom rules we typically add to boost speed further, see this article.
    The $5/month plan includes Cloudflare’s APO service that does edge caching. With edge caching, entire pages from your site are stored on Cloudflare’s servers (aka “edge”) which removes most of the impact of geography on site speed AND can increase the volume of traffic your site can handle from 2-50x
    On the $20/month plan (which we recommend for bigger sites) Cloudflare also provides a full firewall, image optimization and bunch of other site speed optimizations.
    If you can’t use Cloudflare, at least use a CDN service (one that has image optimization built-in like Bunny CDN). CDN is very useful in speeding up the response of static assets such as CSS, JS, images, and fonts.

    1. Make Sure Your Database Is Using the Innodb Storage Engine for All Tables
      InnoDB and MyISAM are “storage engines” used by MySQL – essentially the format the database stores its database. MyISAM was a default table type until MySQL 5.5.5 was introduced in 2010. Innodb tables are faster than MyISAM so ensuring the tables are using the Innodb storage engine can dramatically speed up queries.

    MyISAM Table

    There are several differences between the two but in simple terms, MyISAM tables will lock a database table while it’s being written to. This means that on a busy site these database write operations start to queue and cause delays in processing which manifest as slower loading to the user.

    Think of the database table as an Excel spreadsheet where if one person has it open, another person can’t make any edits.

    Innodb tables only lock the row in the database table that’s being written to, so there’s little to no database queuing. It’s like using a shared Google Sheet that multiple users can work on at once.

    Converting from MyIsam tables to Innodb tables can give you a solid speed boost particularly in the backend and on higher traffic sites.

    InnoDB Table
    For most affiliate sites, the database will be a few hundred megabytes at most, so we use a plugin called Servebolt Optimizer (https://wordpress.org/plugins/servebolt-optimizer/ ) to do the conversion. If your database is over 1 GB in size, you might need to run the convert operation a couple of times.

    If the database is big, e.g. several GB, don’t do this during peak times, and probably not a good idea to do the conversion using this plugin as you’ll wind up knocking over the server for a reasonably long period of time. Better to do this at the database level itself in PHPMyAdmin and probably wise to get a developer to do this for you.

    1. Disable Any Plugins and Tools You’re Not Using
      Unused plugins and tools might be another reason for slow WordPress database queries, especially when it comes to older websites. Go through all plugins and tools your site uses, and delete or disable those that are no longer used.

    From a speed point of view, cutting the number of plugins should improve your site’s performance.

    1. Delete Expired Transients for Your Database
      The transients API in WordPress makes way for developers to store temporary information in the WordPress database and assign it an expiration time, after which it will be deleted. This eases server load and improves WordPress performance.

    Sometimes, transients expire or disappear before their set timeframe, or don’t have the expiring time. Old and expired transients can increase the site load and negatively influence its performance. There’s a number of different plugins that can delete expired transients, like WP Rocket as well as WP Optimize.

    1. Use the Query Monitor Plugin to Identify Database Hogs
      Query Monitor is a WordPress plugin that allows debugging WordPress’ slow database queries, hooks and actions, PHP errors, editor blocks, HTTP API calls, enqueued scripts and stylesheets, and more. It also helps you to efficiently find out if plugins, themes, or functions perform poorly. Query Monitor comes with some advanced features that are extremely useful with debugging Ajax calls, REST API calls, and user capability checks.

    Query monitor home page
    Installing the Query Monitor plugin and performing operations on the frontend and backend of the site will identify slow pages, large database queries and memory hogs.

    Query Monitor is free – https://wordpress.org/plugins/query-monitor/

    1. Update All Plugins to the Latest Versions
      This is yet another way to speed up WordPress data queries. Quite often older plugins have minor incompatibilities with the current WordPress version or PHP version being used. Usually these issues will appear in Query Monitor but occasionally not. Making sure all plugins are up to date can eliminate these problems.

    Pay special attention here to paid plugins that come from Themeforest/Envato or a third party where there may be several updates available but the plugin itself does not show any updates available.

    1. Analyze Server Logs to Identify Any Resources Getting Hammered
      Sometimes looking at server log files can help identify particular resources that are getting hammered or errors happening under the bonnet.

    Again the Query Monitor plugin will usually unearth errors that would show up in the server log but occasionally not.

    Often we find SEO crawlers hammer Woocommerce sites adding and removing thing to the cart and wishlist rapidly over the course of a few seconds chewing up a huge volume of server resources so blocking these crawlers can be useful. Likewise brute-force attacks on the WordPress backend login screen can have a similar effect.

    1. Reduce Load Further by Using Wordfence or Another Security Tool
      As per the previous point, using security tools can help reduce the volume of scrapers, crawlers and otherwise nefarious visitors chewing up server resources.

    Typically we recommend using the $20/month version of Cloudflare which has a true stateful firewall built into it so it can intelligently block traffic as well as the free version of Wordfence which will help reduce brute force attacks and anything that slips through Cloudflare.

    Further help….
    I hope you found this post useful. If you’re looking for help specifically with high database load, our Consult Services is probably the service that can help you. If you’re unsure, head to the homepage and submit a free site speed audit request.

    Want to go faster, rank higher in Google & get more customers?
    Sign up now and join 1000s of other subscribers and get cutting edge tactics & techniques we’ve learnt after optimizing 4000+ websites