Optimization – WP Speed Matters https://wpspeedmatters.com Wed, 06 Jul 2022 05:25:36 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.2 https://wpspeedmatters.com/wp-content/uploads/2019/07/favicon-50x48.png Optimization – WP Speed Matters https://wpspeedmatters.com 32 32 How to Speed Up Background Images https://wpspeedmatters.com/speed-up-background-images/ https://wpspeedmatters.com/speed-up-background-images/#respond Thu, 31 Dec 2020 06:13:30 +0000 https://wpspeedmatters.com/?p=3877 Background images are usually used in places that have some text or content on top. It can be a slider, a featured image of the blog post (like below) or a hero image.

Chances are they’re loading slow and can affect user experience due to the increase in Largest Contentful Paint (LCP) if they’re in the above fold.

featured image wpsm

Why are Background Images Slow?

Low priority requests

If the image is inside an external CSS file, it will be downloaded only after downloading and parsing the CSS file, and when the CSS class is actually used in HTML.

This can reflect in your core web vitals metric like Largest Contentful Paint (LCP) if those background images are in the above fold.

If it’s an IMG tag, the image is downloaded instantly when HTML is parsed.

Hard to Lazy Load & Preload

IMG tags can leverage native browser lazy loading, which doesn’t require any JavaScript.

You can still lazy load background images if they’re in HTML as an inline style. Plugins like FlyingPress automatically detect and lazy load them.

However, if the background image is inside an external CSS file or internal, things will get tricky as we can’t figure out whether an HTML element has a background image or not.

Note: If you’re using FlyingPress, we have a helper class “lazy-bg” to lazy load background images even inside CSS files.

How to Speed Up Background Images?

Use IMG tag with object-fit

Background images are commonly used in sliders with some text/content in the centre, or you have a fixed div, and you want to place an image that will ‘fill’ without resizing area (background-size: cover).

Previously it was really hard to achieve this with IMG tags. So using background images made sense.

However, there is a new CSS property object-fit: cover that gives with the same benefit. Browser support is also good.

img object fit

Preload background image

Whether you’re using a background image or IMG tag if the image is in the above fold, preload that image. Preloading tells the browser to download that image on high priority.

preload bg

IMG tag with ‘display: none’ hack

Background images can be used in conjunction with background-colorbackground-repeatbackground-attachmentbackground-position, and background-blend-mode etc.

So in some situations, it’s better to use background-image instead of an IMG tag to leverage other CSS properties.

You can add a normal IMG tag with display: none. This will tell the browser to download the image immediately, but display it using a background image.

img inside style

Add responsive images

You add srcset and sizes to normal images to deliver responsive images based on the device:

<img srcset="elva-fairy-320w.jpg 320w,
             elva-fairy-480w.jpg 480w,
             elva-fairy-800w.jpg 800w"
     sizes="(max-width: 320px) 280px,
            (max-width: 480px) 440px,
            800px"
     src="elva-fairy-800w.jpg" alt="Elva dressed as a fairy">

Similarly, you can do the same for background images using image-set:

bg image set

Otherwise, you will be delivering the same large image for a 2880px MacBook and 750px iPhone 6s!

Inline background image in HTML

If your background image is inside an external CSS file, inline it in the HTML. This way browser doesn’t have to wait for downloading that CSS file and then download the image.

externa internal vs inline

Further Reading

]]>
https://wpspeedmatters.com/speed-up-background-images/feed/ 0
9 Tips to Improve FCP in WordPress https://wpspeedmatters.com/improve-fcp-in-wordpress/ https://wpspeedmatters.com/improve-fcp-in-wordpress/#comments Tue, 14 Jan 2020 17:24:00 +0000 https://wpspeedmatters.com/?p=3245 Google recently made an announcement that they’re ranking websites based on FCP and FID.

They categorize websites into Slow, Moderate and Fast

fcp and fid

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

site speed search console

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

crux data Jan 14

“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:

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 FlyingPress and a good hosting provider like Cloudways.

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 FlyingPress 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.

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.

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

Preload Pages in the Background

By preloading pages in the background, whenever 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">

Use plugins like Flying Pages which will automate this task intelligently.

Flying Pages cover

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. If you’re using Flying Images, you can exclude images by keywords which can be file names, class, id, attribute or even from the parent node of the image.

flying images settings

Inline ‘Critical’ Images

Inlining images mean 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]..."/>

If you take a look at the home page of my blog, you’ll see a few images that I’ve inlined:

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.

render tree construction

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

Ensure Text Remains Visible during webfont load

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

fonts error goole psi

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).

Demo:

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.

Comment below if you’ve any queries or feedback. I read and reply to each of them within 8 hours!

]]>
https://wpspeedmatters.com/improve-fcp-in-wordpress/feed/ 1
How to Reduce DOM Size in WordPress https://wpspeedmatters.com/reduce-dom-size-in-wordpress/ https://wpspeedmatters.com/reduce-dom-size-in-wordpress/#comments Mon, 25 Nov 2019 15:45:32 +0000 https://wpspeedmatters.com/?p=3008 When analyzing your site through Google PageSpeed Insights you might have seen an error like “Avoid an excessive DOM size”:

excessive dom size google pagespeed

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

dom size

What is DOM?

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.

render tree construction
Image credits: Google Developers
  • Nodes – All HTML elements in the DOM are called Nodes. (aka “leaves” in the tree).
  • Depth – How long does the “branch” goes in a tree is called the depth. For example, in the above diagram, “img” tag has a depth of 3. (HTML -> body -> div -> img).
  • Child Elements – All the child nodes of a node (without any further branching) are child elements.

Lighthouse and Google PageSpeed Insights starts to flag pages if any of the following conditions are met:

  • Have more than 1,500 nodes in total.
  • Have a depth greater than 32 nodes.
  • Have a parent node with more than 60 child nodes.

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 styles rules make a huge work for the browser. The browser has to parse the HTML, construct 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 Reduce 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 Reduce 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.

Here is how to lazy render contents using FlyingPress:

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.

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 has 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.

Comment below if you’ve any queries or feedback. I read and reply to each of them within 8 hours!

]]>
https://wpspeedmatters.com/reduce-dom-size-in-wordpress/feed/ 11
Improving HTML Cache Hit Ratio by Ignoring Query Strings https://wpspeedmatters.com/ignore-query-strings/ https://wpspeedmatters.com/ignore-query-strings/#comments Mon, 11 Nov 2019 11:04:21 +0000 https://wpspeedmatters.com/?p=2868 Just because you have the highest scores or the fastest fully loaded time doesn’t mean your actual visitors have the fastest site.

You must have set up caching via cache plugins or Cloudflare page rules to cache HTML pages. But are you sure that these cached pages are delivered to your visitors?

In my case, visitors from Facebook were not receiving cached pages.

The problem was, Facebook is appending a query string “fbclid” to all links from Facebook. It’s unique for each user.

Screenshot 2020 04 07 at 9.09.32 AM

So every time there is a new “fbclid”, they’re getting uncached pages.

In LiteSpeed Cache

LiteSpeed Cache caches query strings by default. You can exclude certain keywords by going to LiteSpeed Cache -> Cache ->Drop Query String:

ls cache query strings

I usually ignore the following:

  • fbclid
  • ref
  • utm*

In FlyingPress

FlyingPress automatically ignores the following query strings:

  • age-verified
  • ao_noptimize
  • usqp
  • cn-reloaded
  • sscid
  • ef_id
  • s_kwcid
  • _bta_tid
  • _bta_c
  • dm_i
  • fb_action_ids
  • fb_action_types
  • fb_source
  • fbclid
  • utm_id
  • utm_source
  • utm_campaign
  • utm_medium
  • utm_expid
  • utm_term
  • utm_content
  • _ga
  • gclid
  • campaignid
  • adgroupid
  • adid
  • _gl
  • gclsrc
  • gdfms
  • gdftrk
  • gdffi
  • _ke
  • trk_contact
  • trk_msg
  • trk_module
  • trk_sid
  • mc_cid
  • mc_eid
  • mkwid
  • pcrid
  • mtm_source
  • mtm_medium
  • mtm_campaign
  • mtm_keyword
  • mtm_cid
  • mtm_content
  • msclkid
  • epik
  • pp
  • pk_source
  • pk_medium
  • pk_campaign
  • pk_keyword
  • pk_cid
  • pk_content
  • redirect_log_mongo_id
  • redirect_mongo_id
  • sb_referer_host
  • ref

You can also add your own query strings to exclude from caching:

ignore query strings

In WP Rocket

WP Rocket automatically ignores the following query strings:

  • All UTM tags (utm*)
  • fb_action_ids
  • fb_action_types
  • fb_source
  • fbclid
  • _ga
  • gclid
  • age-verified
  • ao_noptimize
  • usqp
  • cn-reloaded

Any other query strings like s=something, country=India, ref=google.com etc are served non-cached pages. So if you want any custom query parameters to be ignored, you’ll need to download their helper plugin.

You can read more about WP Rocket‘s query caching here.

In Swift Performance

Swift Performance by default ignores “fbclid” and “gclid“. There is also an option to ignore all other query strings. But will break search and similar pages.

Noway to selectively ignore using keywords.

query strings swift performance

Will Google Analytics, Facebook and other trackers work after this?

Tracking scripts like Google Analytics, Facebook Pixel etc use these query parameters for various purposes. Since you’re not removing them, these scripts can get those from the URL and do necessary.

Note: For Cloudflare, this doesn’t apply because you’ll need to remove query strings.

Cloudflare Full Page Caching

If you’ve implemented full page caching via rules in Cloudflare, a similar issue exists. Most of your visitors from Facebook and other sites with these query strings are getting uncached pages.

To fix this you’ll need to add a Page Rule that will remove such query strings.

Here is an example rule that will remove “fbclid” query string:

cloudflare ignore fbclid

This tells Cloudflare to redirect URLs like https://wpspeedmatters.com/hire-me?fbclid=xxxxxx to https://wpspeedmatters.com/hire-me.

Thanks to Gulshan Kumar for posting this tip in our group.

Conclusion

WP Rocket and Swift Performance handle this really well by default. In LiteSpeed Cache, you just need to add the necessary keywords to exclude list.

However, if you’re using Cloudflare full page caching, you might need to buy additional Page Rules to set it up.

Comment below if you’ve any queries or feedback. I read and reply to each of them within 8 hours!

]]>
https://wpspeedmatters.com/ignore-query-strings/feed/ 1
How to & When to Inline Images using Base64/SVG in WordPress https://wpspeedmatters.com/base64-images-in-wordpress/ https://wpspeedmatters.com/base64-images-in-wordpress/#comments Mon, 07 Oct 2019 05:37:24 +0000 https://wpspeedmatters.com/?p=2528 One of my primary goals in optimizing a website is to improve first contentful paint and first meaningful paint, make the above fold content visible as fast as we can.

Ideally, the browser should be able to render and paint above fold content with least amount of HTTP requests. Generating critical path css, deferring css and js help a lot.

One of the similar techniques I use to improve first meaningful paint is inline base64 and SVG images.

What are Base64 Images?

Base64 is a kind of binary-to-text encoding. In other words, any data represented as text. In our case, images are represented as text. Any image can be converted to base64.

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]..."/>

base64-image.de is a nice tool to convert images to base64.

What are SVG Images?

SVG (Scalable Vector Graphics) is another image format that is represented as code in an XML-based format. It’s ideal for vector images. Usually logos, icons are vector images.

The SVG contains codes for drawing shapes like paths, outlines, curves etc. Hence the size of SVG is usually much lower than JPG/PNG/GIF.

An SVG image in HTML:

<img src="logo.svg"/>

An inlined SVG image in HTML:

<svg xmlns="http://www.w3.org/2000/svg">...[content]...</svg>

What’s Wrong in Inlining Images?

You need carefully pick which images should be inlined.

Here are some pitfalls in inlining images:

  • Converting images to base64 results in a 30% increase in size.
  • Size of HTML page increases (too much will affect TTFB)
  • Images cannot be delivered via CDN.

Regardless of all this, there some good places to inline images.

When to Inline Images?

I’ll show you where I’ve inlined images in my blog:

inlined images screenshot

The three images that I inlined are:

  • Logo – SVG, 2.5 KB
  • Search icon – SVG, 0.2 KB
  • FB group pic – PNG, 4.5 KB. After converting to base64 – 6 KB

My HTML size increased from 19 KB to 25 KB (Thanks to brotli compression).

Keep your HTML size under 100 KB. Beyond that will slightly lower TTFB. Also if you’re caching HTML pages in Cloudflare, this isn’t an issue.

Logos, icons and other images in the above fold are ideal for inlining images.

Inlining Images in WordPress

Let’s make our images ready for inlining:

If you’re able to edit the URL of the image, you can directly paste the base64 text:

base64 gutenberg

However, some of the images/icons are hardcoded into theme/plugins. In that case, you need to find out the right file and replace the code

What I usually do is, find the class name of the corresponding image (or the parent element) and search for the file in theme/plugin.

String locator is a nice plugin to do this. It will search for the string inside files and you can edit it.

string locator
inlined svg image

Conclusion

Inlining images is little tricky based on your theme/plugin and has some pitfalls as I discussed above. But if you pick the right images and do it correctly, it can give you great results.

Try it out yourself.

Comment below if you’ve any queries or feedback. I read and reply to each of them within 8 hours!

]]>
https://wpspeedmatters.com/base64-images-in-wordpress/feed/ 1
How to Setup External Cron Jobs in WordPress for Performance https://wpspeedmatters.com/external-cron-jobs-in-wordpress/ https://wpspeedmatters.com/external-cron-jobs-in-wordpress/#respond Sun, 06 Oct 2019 06:50:06 +0000 https://wpspeedmatters.com/?p=2523 What are Cron Jobs?

Cron is software in Linux OS to schedule time-based jobs. For example, check for emails, create backups, check for updates, send error logs to 3rd party providers etc.

Cron is run by ‘crontab’ (cron table), a file with configurations of the jobs to run.

Below is the example of a job in the crontab file:

00 11 * * * /home/backups/scripts/log_backup.sh

This tells the OS to run the ‘log_backup.sh’ every day at 11:00. Here is how it works in detail:

# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of the month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12)
# │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday)
# │ │ │ │ │
# │ │ │ │ │
# │ │ │ │ │
# * * * * * command to execute

Why WordPress needs Cron Jobs?

You might have already guessed it!

Here are a few use cases where WordPress itself or some plugins use cron jobs:

  • Check for plugins/themes/core updates
  • Scheduled blog posts
  • Create backups
  • Optimize database tables
  • Send emails
  • and much more…

What’s wrong about inbuilt WordPress Cron?

WP-Cron is Cron for WordPress. However, the working of WP-Cron is different than the cron that I mentioned above.

There are some technical difficulties for WordPress to set cron jobs in the crontab file. So WP-Cron is not based on the server cron. Instead, it checks for any jobs every time a user visits your posts or pages and execute it.

Zero visitors = Zero Cron runs

You scheduled to send an email report (via some plugin) every day at 6 pm. But what if there is no visitor at that time?

More visitors = Unnecessary Cron runs

Suppose your site is receiving 10 pages views every second. Then WP-Cron checks for cron jobs 10 times every second.

Checking and running cron jobs involves PHP execution. As you know it’s resource hungry and will make your site slow as your traffic increases.

A better approach is to use you the above-mentioned system’s cron job and disable WP-Cron.

How to disable WordPress inbuilt Cron Job?

Before we set up external cron jobs, let’s disable the inbuilt WP-Cron.

Open wp-config.php from your file manager and add the following code on top of the file:

define('DISABLE_WP_CRON', true);

How to setup external Cron Jobs in WordPress?

We’ve to call https://domain.com/wp-cron.php?doing_wp_cron every x mins. There are different ways to set it up based on your hosting.

Using EasyCron (easiest way)

EasyCron is a service that lets you create cron jobs easily. The free plans let you create cron jobs that run every 20 mins. That’s more than enough for most of the sites.

easycron wordpress setup

Using cPanel

Open ‘Cron Jobs’ from cPanel:

cron job cpanel

Add a new cron job as follows:

add cron job cpanel

For the command, use the following code (replace domain.com with yours):

wget -q -O - https://domain.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1

In a VPS server

SSH into your VPS server and enter the command:

crontab -e

This will open the crontab file. Now add the following command into that file and exit (:wq to exit editor):

wget -q -O - https://domain.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1

Closte

cron jobs closte

Kinsta

SSH into the server and follow the steps in ‘In a VPS server’. You can also contact support to do this.

Cloudways

Open your application and goto to ‘Cron Job Management’ to create a new cron job.

Select the type as ‘PHP’ and add ‘wp-cron.php?doing_wp_cron’ to the command:

cloudways cron job

SiteGround

Follow the steps in ‘Using cPanel’ as above.

Conclusion

Enabling external cron jobs help to reduce resource usage, give better performance and run jobs more reliably and on time.

Comment below if you’ve any queries or feedback. I read and reply to each of them within 8 hours!

]]>
https://wpspeedmatters.com/external-cron-jobs-in-wordpress/feed/ 0
How to Serve Images as WebP in WordPress (3 Methods) https://wpspeedmatters.com/serve-webp-in-wordpress/ https://wpspeedmatters.com/serve-webp-in-wordpress/#comments Wed, 25 Sep 2019 05:54:19 +0000 https://wpspeedmatters.com/?p=2437 If you’ve analyzed your site via Google PageSpeed Insights, you must have probably seen the error “serve images in next-gen formats”. Well, WebP is that next-generation format.

WebP error PageSpeed Insights

However, delivering images WebP isn’t that easy. It depends on your server web server, cdn of choice, theme, cache plugins etc.

This guide helps you to deliver images as WebP in WordPress in 3 methods.

What is WebP?

A new image format for the Web

Google

WebP is an image format (just like png and jpg), developed by Google. Images in WebP format (.webp) are generally much smaller, which makes websites faster and use less bandwidth.

Depending on the image, you may get a reduction of 25% to 70% in size.

webp convert

JPEG, PNG, GIF etc have their own pros and cons. The table below will give you an idea:

JPGGIFPNGSVG
Vector❌❌❌✅
Raster✅✅✅❌
Transparency❌✅✅✅
Animation❌✅✅✅
Lossy✅❌❌❌

WebP comes with almost all the features mentioned above! Then why can’t we use WebP everywhere?

Why not use WebP everywhere?

webp support
WebP Browser Support

As you can see only 80% of the devices only supports WebP. Not just outdated browsers, Safari/iOS Safari still doesn’t support WebP.

Why serving WebP is hard?

As you’ve noticed we’ve to deliver images according to the browser. If the browser doesn’t support WebP, we’ve to serve them the original image (jpg/png/gif).

There are mainly two ways to serve WebP:

Using picture tag

We can use picture tag to tell the browser that we do have WebP format. If the browser supports it, it will be fetched otherwise normal/fallback image.

<picture>
  <source srcset="img.webp" type="image/webp">
  <source srcset="img.jpg" type="image/jpeg"> 
  <img src="img.jpg">
</picture>

By varied response

In varied responses, you have a single file as usual. Just like this:

<img src="img.jpg" />

The single image URL is capable of delivering jpg and webp. It’s done by the server.

Even though its file extension is ‘.jpg’, if the browser support WebP, then its response will be WebP. Also called ‘varied response’.

Picture tag vs Varied response

Each has its own pros and cons. Here is a comparison table:

Picture tagVaried response
Works with background images❌✅
CDN friendly✅✅ (only a few)
Need to configure the server❌✅ (Nginx)
Works with lazy loading✅✅

How to Serve Images in WebP in WordPress?

Method #1 – Use CDN with only the fly WebP conversion

This is probably the easiest solution. Some CDN providers nowadays support converting images to WebP on the fly, along with image optimization.

Here are a few:

You can also save some disk space using this method since you don’t need to store both normal and converted WebP images.

BunnyCDN

BunnyCDN comes with ‘Bunny Optimizer’ which can compress images and convert them to WebP on the fly.

bunnycdn optimization

Method #2 – Using varied response + CDN

As described above ‘varied response’ will have a single image URL that is capable of serving both WebP and non-webp images based on the requested browser.

We also need to pick the right CDN that supports WebP request headers as a cache key. Otherwise once the WebP image is cached in the server, the same will be delivered to browsers that don’t support WebP.

Setup varied response in WordPress

The easiest way to set up the varied response for WebP in WordPress is via WebP Express plugin. Just install the plugin and click ‘Save settings and force new .htaccess rules’.

WebP Express Settings

WebP Express will set up a WebP converter and rewrite rules so that on receiving the request it will convert images to WebP on the fly and if the browser doesn’t support WebP, the default image will be delivered.

If you’re in Nginx

WebP Express adds necessary ‘.htaccess’ rewrite rules, but it only works in Apache or LiteSpeed or OpenLiteSpeed server. If you’re in Nginx, you’ll need to edit nginx.config and add the following code:

# WebP Express rules
# --------------------
location ~* ^/?wp-content/.*\.(png|jpe?g)$ {
  add_header Vary Accept;
  expires 365d;
  if ($http_accept !~* "webp"){
    break;
  }
  try_files
    /wp-content/webp-express/webp-images/doc-root/$uri.webp
    $uri.webp
    /wp-content/plugins/webp-express/wod/webp-on-demand.php?xsource=x$request_filename&wp-content=wp-content
    ;
}

# Route requests for non-existing webps to the converter
location ~* ^/?wp-content/.*\.(png|jpe?g)\.webp$ {
    try_files
      $uri
      /wp-content/plugins/webp-express/wod/webp-realizer.php?wp-content=wp-content
      ;
}
# ------------------- (WebP Express rules ends here)

The above code adds necessary response headers (vary and cache-control) and try to deliver WebP if exists, otherwise, forward it to converter (based on the browser support)

CDN providers that support ‘Varied response’

If your CDN provider doesn’t support WebP as a cache key, then WebP files will be delivered to non-webp supported browsers. Similarly, there are also chances that non-webp images will be delivered to supported browsers.

BunnyCDN, KeyCDN, Google CDN and many other CDN providers support WebP as a cache key. Make sure you enable them in settings.

In BunnyCDN:

bunnycdn webp cache key

In KeyCDN:

keycdn webp cache key

Using Cloudflare free plan?

Unfortunately, Cloudflare free plan doesn’t support WebP as a cache key. Either use a CDN like BunnyCDN or upgrade to their pro plan.

Make sure WebP Express is installed.

  • Kinsta or WP Engine – Contact their support to add the above Nginx config and enable cache WebP cache key in their CDN (KeyCDN).
  • Cloudways – Installing WebP Express and saving settings with ‘.htacess’ is enough. Since Cloudways uses a hybrid approach of Apache + Nginx, it works out of the box.
  • SiteGround – Contact support to add Nginx config. Use a supported CDN as mentioned above.
  • LiteSpeed/OpenLiteSpeed/Apache server – Installing WebP Express and saving settings with ‘.htacess’ is enough. Also, use a supported CDN as mentioned above.
  • Custom VPS with Nginx (LEMP stack) – Configure nginx.conf and use a supported CDN as mentioned above.

Method #3 – Using picture tag

If both of the above methods don’t work for you, you can use the picture tag. It doesn’t require any server configuration (editing nginx.conf) and it supports all CDN providers.

If you use this method, all img tags will be converted to something like this:

<picture>
  <source srcset="img.webp" type="image/webp">
  <source srcset="img.jpg" type="image/jpeg"> 
  <img src="img.jpg">
</picture>

If the browser supports WebP, the corresponding file is delivered, otherwise normal image.

Setup picture tag for WebP in WordPress

The easiest way to set up a picture tag is via WebP Express.

Set the operation mode to ‘CDN friendly’ and turn on ‘Alter HTML’

webp express picture tag

Conclusion

I wish there will be a day where all browsers support WebP!

If you can spend a few dollars a month, then the easiest and efficient way is to use a CDN like FlyingCDN that will convert images to WebP on the fly. Otherwise, stick with method #2 I mentioned above.

Comment below if you’ve any queries or feedback. I read and reply to each of them within 8 hours!

]]>
https://wpspeedmatters.com/serve-webp-in-wordpress/feed/ 10
14 Tools I Use to Audit Performance of a WordPress site https://wpspeedmatters.com/performance-audit-tools-for-wordpress/ https://wpspeedmatters.com/performance-audit-tools-for-wordpress/#respond Fri, 19 Jul 2019 06:22:21 +0000 https://wpspeedmatters.com/?p=2132 Performance is not just about “my site loads under x seconds”. There are several other factors you need to look into.

Here is a list of tools and services I use to audit or test the performance of a WordPress site. Not just WordPress, these can be used for any site.

Your Eyes – The Eye Test

Don’t get me wrong.

Let’s take an example, Flying Pages WordPress plugin. It helps to prefetch inner pages in the background and loads pages instantly on user navigation. This gives a much better user experience.

I haven’t seen any tools who can measure these.

Whether your tools give you the perfect score or loads in a few hundred milliseconds, always test your site through naked eyes.

Chrome Developer Tools

Google Chrome Developer Tools comes with several handy tools to audit a website. Open developer tools by Ctrl+Shift+I or Ctrl+Opt+J.

Network Monitor

Network monitor gives a detailed view of what all requests are made by the browser, its response, timings etc.

  • Status – Easy to figure out if any resource is not available
  • Protocol – Checks HTTP1.1, HTTP2, Quic etc
  • Type – File type returned, easy to figure out WebP is working
  • Size – Amount of data transferred, with and without Gzip. ‘Disk Cache’ or ‘Memory Cache’ indicates browser caching is working
  • Priority – Priority of each file which browser requests. CSS, JS, Fonts have high priority, images – Low, SendBeacon (Google Analytics), prefetch (Flying Pages) have the lowest.
  • Waterfall – A waterfall of the data requested and received. Also, provide in-depth data of DNS lookup, TCP connection, SSL, TTFB, etc. Easy to debug lazy loading too
chrome dev tools network

Audits

Test your site for performance, PWA, best practices, accessibility and SEO. You can also choose device and throttle network speed and CPU.

You can use the ‘Lighthouse’ tool which I mentioned below to get the same results.

chrome dev tools audits

Security

How does security relate to performance?

The version of TLS can dramatically affect the TTFB. The latest version is TLS 1.3.

chrome dev tools security tls

Google PageSpeed Insights

Google PageSpeed Insights is one my favourite tool among all. What I like about it is, instead of just focussing on ‘load time’, it measures user experience up to a point.

Some people complain that it doesn’t show fully loaded time. I believe Google doesn’t show it because it’s not a good way to measure a site.

google page speed insights

Google PSI is one of the best tools to analyze:

  • TTFB – Time to First Byte (server response time)
  • FCP – First Contentful Paint
  • FMP – First Meaningful Paint
  • TTI – Time to Interactive

and more

GTmetrix Analyzer

GTmetrix will analyze your site and can recommend what all things are needed to be fixed. Also, give you some scores and fully loaded time. You can also choose the region for test, device, browser etc.

gtmetrix report

GTmetrix provides a Waterfall of all the requests made from the website, which I found very useful.

gtmetrix timeline

Most of the time people look into scores and fully loaded time. The factors that I mainly look into are in the ‘Timings’ tab.

gtmetrix timings

GTmetrix Monitor

GTmetrix also comes with a monitor that will periodically check your site and send you a weekly digest. I no longer have to analyze my site again and again if I update something in my site.

Their free plan (Basic plan) provides 3 URLs to monitor.

gtmetrix monitor

Pingdom Speed Test

Pingdom Speed Test is a free tool provided by the SolarWinds. It’s is very similar to GTmetrix, provide you with a report with scores and load time.

pingdom report

But what I like about this tool is that it shows a breakdown of size and no. of requests per domain, file type etc. This gives a quick view of where to optimize.

pingdom breakdown

Pingdom Monitoring

What if your server is going down occasionally or your site is inaccessible to some users on heavy traffic?

Pingdom is a ‘Website Performance and Availability Monitoring’ company. Pingdom monitor will continuously monitor (say every 5 mins or 30 secs) and will alert you if something goes wrong.

There is no free plan. Paid plan starts at $14.95/month.

pingdom monitor

WebPageTest

WebPageTest is one of the oldest and reliable tools. Test your website multiple times from the same device. It’s very useful to see how effectively “browser caching” is working. Also provide some key metrics like TTFB, keep-alive, compression, browser caching, cdn etc.

I’m not a big fan of their UI 😉 so I don’t use it that often.

webpagetest results

KeyCDN Performance Test

Most of the tools I listed above will test TTFB (time to first byte or server response time) from a single location. KeyCDN Performance Test will analyze your site from 14 locations with just a button click and provide a report of DNS lookup time, connection, TLS and TTFB.

tls 1.3 ttfb

Uptime Robot

Similar to Pingdom Monitoring, Uptime Robot monitors your site for the downtime and will alert you.

The free plan allows 5 mins of monitoring intervals.

uptime robot dashboard

Google Analytics Site Speed

Google Analytics uses HTML5 Navigation Timing API to collect performance metrics from 1% of your users (configurable). You can view it under Behaviour -> Site Speed.

What’s so special about GA Site Speed is that data is collected from real-world usage. All other tools use the high-performance network or an emulated network to do the test, which might be different from real users. What if most of your users are still on 3G?

google analytics site speed

Loader.io

What if one of your blog posts went viral? Are you sure that your server/hosting provider could handle it? You might be losing a good amount of users and affecting SEO badly without your knowledge.

Don’t assume and believe in “unlimited” traffic. Better do a load test and figure out how many visitors you can handle.

Loader.io makes it easy to send 10k requests/second to your site and see how it performs.

openlitespeed load test 1

dotcom-tools

dotcom-tools tests your site from 25 locations, both first and repeat first. I also use this tool to prebuild cache of CDN after a purge.

dotcom tools

Lighthouse

Lighthouse is another tool provided by Google. It’s built inside Google Chrome.

Lighthouse tests Performance, Accessibility, Best Practices and SEO. The ‘Performance’ report will be the same as in Google PageSPeed Insights. But in a single tool, you can test all of them.

You can test it directly from your Chrome Browser’s ‘Audits’ tab in developers tools or go to https://web.dev/measure

lighthouse report

Do you use any other tools?

Comment below if you’ve any queries or feedback. I read and reply to each of them within 8 hours!

]]>
https://wpspeedmatters.com/performance-audit-tools-for-wordpress/feed/ 0
4 Levels of Image Optimization in WordPress https://wpspeedmatters.com/image-optimization-in-wordpress/ https://wpspeedmatters.com/image-optimization-in-wordpress/#comments Thu, 06 Jun 2019 06:42:23 +0000 https://wpspeedmatters.com/?p=1394 Why you should Optimize Images?
image size over web

I hope the above picture should give you some idea.

As technology grows, the camera quality has improved a lot. Even new mobiles like iPhone, OnePlus will capture images at resolution 4032 x 3024 pixels, and the size of few MBs. Normal devices like desktop may have a width of 1500-2000 pixels and mobiles up to 800 pixels.

Optimizing images can reduce 50 – 70% of your total web page size and speed up total load time by 2x or 3x.

Use Next-Gen Image Formats

You must already aware of the image formats JPEG, PNG and GIF. But these are not the only options and the best.

WebP

WebP is a new image format that is developed by Google. Any image of the format JPEG, PNG, GIF can be converted to WebP which will reduce the size up to 90%.

Here is a comparison:

boy
JPEG 80KB (1000 X 672 PX)

boy
WebP 35KB (1000 X 672 px)

As you can see the same image when converted to WebP resulted in a 57% decrease in size.

Even though WebP is fairly new, it’s supported by most of the modern browsers.

webp support

WebP in WordPress

The easier way to deliver WebP is via a CDN (recommended, discussed below). But if you’re not ready for a CDN due to some reason, you can install the WebP Express WordPress plugin that will do the job.

SVG

SVG is a vector image format, while JPEG, PNG, GIF, WebP are raster images. If you’re not sure about what these are, SVG images are images represented as code. Browser paints the image looking at this code. It will not lose quality however you zoom in.

mfy logo
PNG 14KB
mfy logo
SVG 4KB

SVG images are ideal for icons, logos, charts, infographics etc. Unlike WebP, not every image can be converted to SVG (technically it’s possible but the result would be a higher size image). SVG images need to be drawn by Adobe Illustrator, Sketch or similar software.

SVG in WordPress

SVG by default is not supported by WordPress. You can install SVG Support that will enable this.

That’s all you need, just upload .svg files like normal images!

Base64 / Inline Images

Any image represented as 64 characters of text is called a base64 image. Hard to understand right?

Let’s take a look at the code. A normal image in HTML looks like this:

<img src="https://example.com/logo.png" width="100px">

Here is how the base64 image looks like:

<img src="data:image/png;base64,iVBORw0KGgoAA......==" width="100px">

Instead of URL, base64 is a string that starts like data:image/png;base64. The first portion represents the type of data. The characters after the comma(“,”) represent our image.

The advantage over URLs is that the data required for rendering the image is already provided in the HTML source code, so the browser doesn’t need to make an extra HTTP request and download the file.

mfy logo
PNG 14KB
waRh9FYQm1nigAAAABJRU5ErkJggg==
Base64 17KB

Pros:

  • No extra HTTP request to download image
  • Faster render
  • Ideal for images in the above fold, logo, placeholders etc

Cons:

  • Converting image to base64 results in a 30% increase of size
  • Couldn’t leverage browser caching

Base64 / Inline Images in WordPress

You can convert any image to base64. Go to https://www.base64-image.de/ and upload your image. After the conversion is complete click ‘copy code’.

In the Gutenberg editor, choose an image and select ‘Insert from URL’ and paste the code we copied. Done!

base64 gutenberg

Compress Images

There are several image encoding algorithms that can compress the images that will reduce the size of the image. It will speed up your website as well saves you a lot of bandwidth.

Here is an example:

boy
80KB

boy compressed
30KB

Both of these images have the same dimensions. But as you can see the size has been reduced from 80KB to 30KB (62%).

If you want to know more about image compression, check out this post from KeyCDN.

Image Compression in WordPress

Using Plugins

There are several plugins available that can compress images. My favourite one is ShortPixel. ShortPixel sends each image to their servers and does the best compression available. They support lossy, glossy and lossless compression. It can also generate WebP.

shortpixel compression
  • ShortPixel (recommended) – Best compression, free up to 100 images/month
  • reSmush.it – Completely free for images with max size 5MB
  • Optimole – Free up to 1GB of images per month

Without Using Plugins

There are several online tools to compress images. The one I commonly use is compressor.io. It’s free, fast, lossy/lossless and supports all formats.

compressor.io

Responsive Images

Your theme might be responsive, but your images maybe not. Delivering an image of width 1500px to mobile of width 800px doesn’t make sense!

Here is an example. Same image delivered in different sizes (let me know if you notice any difference).

boy
80KB (1000 x 672 px)

boy resized compressed
9KB (350 x 235 px)

Usually, an image added to HTML looks like this:

<img src="elva-fairy-800w.jpg" alt="Elva dressed as a fairy">

The problem with this approach is that whether users device is mobile or desktop, the same large image will be delivered.

HTML supports srcset for images which tells the browser which image to load based on the device width/PPI.

Images with SRCSET:

<img srcset="elva-fairy-320w.jpg 320w,
             elva-fairy-480w.jpg 480w,
             elva-fairy-800w.jpg 800w"
     sizes="(max-width: 320px) 280px,
            (max-width: 480px) 440px,
            800px"
     src="elva-fairy-800w.jpg" alt="Elva dressed as a fairy">

You can check whether your theme supports srcset by right-clicking on any image and select ‘Inspect Element’. It will look something like this:

srcset wordpress

What if my theme doesn’t Support SRCSET?

You got three options:

  • Ask your theme developer to fix it!
  • Use plugins that will add srcset, like FlyingPress
  • On the fly image resizing via CDN (recommended, discussed below)

Image Delivery via CDN

So you optimized everything with next-generation image, compression, resizing and all. But what if there is network latency or the server is slow?

What is a CDN?

If you’re new to CDN, these are content delivery networks specially designed for delivering static files like images. What they do is save a copy of your image in their 100+ servers all around the globe. When someone requests an image, it’s delivered from the nearest server. Thus reducing network latency.

bunnycdn locations

How to Pick a CDN for Images?

There are several free and paid CDN providers. However, not everyone is good at delivering images.

Here are the factors that you need to look for before choosing a CDN:

  • On the fly image compression
  • On the fly image resizing
  • On the fly WebP conversion

If you’re using FlyingPress, there is a FlyingCDN addon that will deliver responsive images with webp conversion, compression and everything:

8 cdn

ShortPixel Adaptive Images is also another option.

Conclusion

So far we’ve covered everything about image optimization. If you’re looking for a quick solution, get FlyingPress with FlyingCDN

Comment below if you’ve any queries or feedback. I read and reply to each of them within 8 hours!

]]>
https://wpspeedmatters.com/image-optimization-in-wordpress/feed/ 2
How to Generate Critical Path CSS in WordPress https://wpspeedmatters.com/critical-path-css-in-wordpress/ https://wpspeedmatters.com/critical-path-css-in-wordpress/#comments Sat, 18 May 2019 17:39:34 +0000 https://wpspeedmatters.com/?p=1237 Understanding WordPress CSS

Before diving deep, let’s understand how the normal CSS works in WordPress.

Every WordPress theme consists of a style.css that contains every bit of code that is necessary to style your website. Theme developers need to support all features of WordPress that consist of blog posts, comments, products page, membership page, forms, etc. Other plugins you install may also add similar css style sheets.

This can make the css files bloated and having a large size of 200KB or even more.

What is Critical Path CSS?

As your CSS files grow, your browser has to download these large files, parse it and render it. Also, know as render-blocking. This will also increase the First Contentful Paint and First Meaningful Paint.

Critical Path CSS is the CSS that is required to render the above fold content of each web page. As the name suggest the “critical” css that helps the browser to paint fast and render it, before downloading the complete css files.

Usually, critical path css is inlined in the head and the original css file is loaded asynchronously or in the footer for the best experience.

Why Critical Path CSS is so important?

You must have already seen the warning from tools like Google PageSpeed Insights or GTmetrix saying “optimize css delivery” or “defer unused css”.

Critical CSS has nothing to do with the page load time. It neither increases/decreases the load time. But gives a much better user experience. It helps to “render” or “paint” the webpage fast.

  • Improves first contentful paint (FCP)
  • Improves first meaningful paid (FMP)
  • Remove unused CSS (not technically remove it, but prioritize “useful” css)

Here are the two screenshots of my blog with and without critical css.

As you can see in “without critical css path”, it took almost 5 seconds to show something useful to the user on the mobile device. The browser has to make an extra HTTP request to the css file, download it, parse it in order to start rendering. But using critical css, all necessary css required is inlined and the browser is able to start rendering right after downloading the HTML file, within a second or less.

How to Generate Critical CSS in WordPress?

There are several ways to generate critical css in WordPress.

Using Cache Plugins

FlyingPress is a premium cache plugin that can generate Critical CSS for each page separately.

3 css

It can also remove unused CSS.

Other Cache plugins that can Generate Critical CSS

WP Rocket, Swift Performance and LiteSpeed cache are similar plugins that can generate Critical CSS. All of these plugins that cloud-based and the entire cache is built in their servers.

Using Autoptimize + Free Critical CSS Generator

There are 3rd party online tools that will provide critical css by entering the URL of your site. pegasaas is such an amazing free tool.

Here is how you can do it:

Step 1: Go to https://pegasaas.com/critical-path-css-generator/ and enter your URL. Copy the generated “Critical Path CSS”.

Step 2: In the Autoptimize settings (turn on advanced settings), under ‘CSS Options’ check ‘Inline and defer css’ and paste the copied css.

critical css autoptimize

Pros:

  • Free

Cons:

  • No separate critical css for different types of pages (e.g.: home page, posts page, category page, product page etc)
  • Do not auto rebuild on theme/customization change

Why WordPress itself can’t generate Critical CSS?

As you have already noticed generating critical path css involves external services. So why WordPress itself can’t generate it?

Generating Critical CSS is made possible by open-source projects like Critical (from Google) or CriticalCSS or penthouse. All these projects are NodeJS based and not in PHP. So you’ll need to install NodeJS on your server. Most of the shared/managed hosting providers will not allow it due to several reasons.

Comment below if you’ve any queries or feedback. I read and reply to each of them within 8 hours!

]]>
https://wpspeedmatters.com/critical-path-css-in-wordpress/feed/ 7