WP Speed Matters https://wpspeedmatters.com Mon, 20 Jun 2022 11:31:06 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.2 https://wpspeedmatters.com/wp-content/uploads/2019/07/favicon-50x48.png WP Speed Matters https://wpspeedmatters.com 32 32 DigitalOcean Premium vs Vultr High Frequency Performance https://wpspeedmatters.com/digitalocean-premium-vs-vultr-high-frequency/ https://wpspeedmatters.com/digitalocean-premium-vs-vultr-high-frequency/#comments Sun, 14 Mar 2021 07:36:25 +0000 https://wpspeedmatters.com/?p=3922 Vultr has a “High Frequency Compute” VPS that has high clock speed and NVMe. It has some excellent performance!

DigitalOcean also recently introduced a similar VPS called “Premium Droplets” powered by Intel and AMD with NVMe SSDs.

So I decided to compare the performance of both with WordPress!

Testing Setup

I created 5 VPS servers in the same region as follows:

  • DigitalOcean Regular – $5/month
  • DigitalOcean Premium Intel – $6/month
  • DigitalOcean Premium AMD – $6/month
  • Vultr Regular – $5/month
  • Vultr High Frequency – $6/month
Screenshot 2021 03 14 at 12.01.05 PM

Running performance test via Google PageSpeed Insights or GTmetrix is not an ideal way to test servers’ performance as it can vary based on several factors.

So I used loader.io to send requests from 0 to 500 clients per second over 1 min.

Screenshot 2021 03 14 at 12.07.38 PM

Test Results

DigitalOcean Regular
DO Intel Regular
DigitalOcean Intel Premium
DO Intel Premium
DigitalOcean AMD Premium
DO AMD Premium
Vultr Regular
Vultr Regular
Vultr High Frequency
Vultr HF

Summary

VPSAverage Response Time
DigitalOcean Regular5.9s
DigitalOcean Intel Premium5.2s
DigitalOcean AMD Premium3.7s
Vultr Regular7.0s
Vultr High Frequency3.1s
DO vs Vultr

Conclusion

Vultr High Frequency has the best performance of all. DigitalOcean AMD Premium is also close.

If I had to choose between these, I would probably go with DigitalOcean AMD Premium as I’ve seen better uptime with DigitalOcean than Vultr.

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

]]>
https://wpspeedmatters.com/digitalocean-premium-vs-vultr-high-frequency/feed/ 11
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
Why you should Self-Host Google Fonts in 2022 https://wpspeedmatters.com/self-host-google-fonts/ https://wpspeedmatters.com/self-host-google-fonts/#comments Wed, 16 Dec 2020 05:52:17 +0000 https://wpspeedmatters.com/?p=3844 Web and browsers are evolving fast!

Many optimizations we did few years are ago now outdated or not recommended.

Delivering Google Fonts to get maximum performance has also changed recently as browsers implemented new features.

I’ve already written a blog post on optimizing Google Fonts. This post is specifically on why you should self-host Google Fonts.

Outdated Performance Arguments

Argument: Browsers will already have Google Fonts cached

When you embed a Google Font, it first downloads a CSS file from “fonts.googleapis.com” and then downloads font files mentioned in that CSS file from “fonts.gstatic.com”.

Only font files downloaded from “fonts.gstatic.com” has a cache period of 1 year. The main CSS file only has 24 hours of cache lifespan.

“Browsers will already have Google Fonts cached”, yes, but to serve that cached font, the browser needs to download a CSS file every 24 hours, that too is render-blocking in most websites!

If that didn’t convince you enough, here is one more 😉.

New “Cache Partitioning” in browsers for privacy

Chrome and Safari have implemented something called “Cache Partitioning” or “double key caching”.

In simple words, files cached by website A will not be available for website B. When a website A downloads a resource from “example.com/script.js”, cache it, and another website B tries to download the same file, it will have to download it again.

So a Google Font downloaded by a website will not be available for another website in the browser cache.

Under the hood, the browser uses a key to cache files. Usually, the cache key is the URL of the file. But with cache partitioning, the URL of the website which requested the file is also included in the cache key.

Without Cache Partitioning

image

With Cache Partitioning

image 1

You can read more about cache partitioning in Chrome here: Gaining security and privacy by partitioning the cache.

Browser implementation of Cache Partitioning

✅ Chrome: since v86 (October 2020)
✅ Safari: since 2013
🚫 Firefox: from v85 (January 2021)

Browsers like Edge, Opera, Brave uses Chromium engine, so expect this feature in other browsers soon.

Also, note that Chrome and Safari alone has a market share of ~80% in browsers.

Argument: Google Fonts delivers optimized fonts based on device/browser

Yes, Google delivers different fonts based on the user-agent.

But as long as you deliver self-hosted Google Font in “woff2” format, you’re targeting ~96% of the browsers.

image 2

Only Internet Explorer and Opera Mini don’t support “woff2”. In that case, you can add “eot” as a fallback and still get all advantages of self-hosting.

Here is the sample code:

@font-face {
  font-family: 'Poppins';
  font-style: normal;
  font-weight: 400;
  src: url('../fonts/poppins-v15-latin-regular.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('../fonts/poppins-v15-latin-regular.woff2') format('woff2'), /* Super Modern Browsers */
}

Argument: Google CDN is faster

If your website on good hosting or has CDN and has enabled HTTP/2, self-hosting will outperform Google CDN. Because the browser doesn’t have to make extra DNS lookups, SSL handshakes etc and reuse existing HTTP/2 connection.

When you self-host and inline Google Fonts, the browser can immediately start to download the font after receiving the first HTML. You can also leverage preload functionality.

Sia Karamalegos has written a great post on comparing the difference: Making Google Fonts Faster⚡.

Image for post
Without Self-Hosting
Image for post
With Self-Hosting

“Yes. The open-source fonts in the Google Fonts catalogue are published under licenses that allow you to use them on any website, whether it’s commercial or personal.”

Google Fonts – FAQ

In fact, Google itself recommends self-hosting Google Fonts for complete control like preloading. It’s mentioned in one of their YouTube videos:

How to Self-Host Google Fonts in WordPress

OMGF plugin can self-host Google Fonts. But I found it hard to use. We’ve to search the fonts or auto-detect by opening pages manually.

If you’re using FlyingPress, turn on “Optimize Google Fonts”. It will take care of self-hosting, combining and everything for you!

5 font 1

Further Reading

]]>
https://wpspeedmatters.com/self-host-google-fonts/feed/ 3
Setup External Cron Jobs using Cron Triggers – Cloudflare Workers https://wpspeedmatters.com/cron-jobs-using-cron-triggers/ https://wpspeedmatters.com/cron-jobs-using-cron-triggers/#comments Tue, 29 Sep 2020 02:05:32 +0000 https://wpspeedmatters.com/?p=3804 Cron Jobs are usually a culprit in some WordPress sites for speed. If you haven’t disabled inbuilt cron jobs, every time a user visits your page, or you open admin area, cron jobs might be exected.

I’ve written more about what are cron jobs, how WordPress uses cron jobs, how to disable inbuilt cron jobs etc in the below blog post. If you haven’t read it, pls read it before going through this tutorial:

This tutorial is for setting up external Cron Jobs using Cloudflare Worker’s new Cron Triggers.

What is Cron Trigger and Service Worker in Cloudflare?

Service Worker – A custom script that can be deployed to their edge network (all PoPs). We can write whatever functionality in there. Code is executed in their edge servers.

Cron Trigger – In UNIX systems (like Linux), ‘crontab’ is a list of commands that you want to run on a regular schedule. Cron Trigger in Cloudflare allows us to execute a service worker on a schedule.

Pricing of Cron Trigger & Service Workers

There is no additional cost for Cron Trigger.

Every time a cron trigger happens, a service worker script is executed. Service Workers comes with a free tier of 10k requests per day.

Let’s say you run a cron job every 10 mins; it only counts 144 requests a day (60/10*24). So, it’s free!

How to Setup Cron Trigger for WordPress Cron Jobs

Goto your account Cloudflare Dashboard -> Workers

image

Click ‘Create a Worker’ and paste the below script:

addEventListener("scheduled", event => {
  event.waitUntil(handleScheduled(event))
})

async function handleScheduled(event) {
  await fetch("https://example.com/wp-cron.php?doing_wp_cron")
}

NOTE: Replace “example.com” with your domain name.

image 1

Click ‘Save and deploy’.

Now, go back and go to the ‘Triggers’ tab and click ‘Add Cron Trigger’.

image 2

By default, it will be ‘Every 30 minutes’. I’ve configured it to every 10 minutes.

Click ‘Save’, and you’re done!

Video Tutorial

Disable WordPress inbuilt Cron Job

Make sure to disable inbuilt Cron Job in your WordPress. Otherwise, there is no point of configuring external cron jobs!

Add the following line to wp-config.php file

define('DISABLE_WP_CRON', true);
]]>
https://wpspeedmatters.com/cron-jobs-using-cron-triggers/feed/ 2
Why I built FlyingPress, how it’s different https://wpspeedmatters.com/why-i-built-flyingpress/ https://wpspeedmatters.com/why-i-built-flyingpress/#comments Tue, 04 Aug 2020 05:56:07 +0000 https://wpspeedmatters.com/?p=3758 I left developing WordPress sites around six years ago.

I mostly build websites using ReactJS, VueJS, and other static site generators after that. It was fun. I’ve full control over everything. When I deploy it, I use Netlify or similar static hosting services, and after updating content, I simply push it to GitHub. Within a few seconds, my site is live on different edge servers all around the world. CDN will cache all pages and static files. I don’t have to worry about minification, caching, image optimization etc. All are just a toggle way. I loved the experience!

I came back to WordPress for creating a blog about development. Yes, static site generators can do it. But I don’t want to reinvent the wheel, and I’m already a big fan of WordPress.

Coming back from static sites, optimizing WordPress is cumbersome. When I left WordPress year again, I was using W3 Total Cache!

Glad to see that there are new cache plugins in the market, like WP Rocket, LiteSpeed cache, Swift Performance etc. All are great, but configuring them is still painful, and the performance is still nowhere near static sites.

When I came back to WordPress for my blog, I asked one of the most expensive hosting providers: “Hey, I’ve traffic from the US and India, my server is in the US, so TTFB to India is pretty high”.

They replied, “there will be network latency since your WordPress site is in the US server.”

I felt something wrong. A lot of updates have happened in the Cloud technologies and seems like WordPress still lags behind.

We need a complete solution that can perform like static sites, without leaving the advantages of WordPress. It should be easy to configure too. Not like W3 Total Cache!

Why not a few more Flying * plugins

When I started building a complete solution called FlyingPress, a few of them asked “why not create more small plugins as you did before, that does one functionality well, as modules. So we can choose accordingly…”

A more number of plugins creates more conflicts. If you’re in our Facebook group, you might see posts every day where one of my plugins conflicted with some other cache plugin.

For example, when using Flying Images and Flying Scripts together, we have to parse the HTML twice, which is slightly resource intensive. If it’s a single plugin that does both of them, we’ve to parse HTML only once.

Another example, when you’ve Cache Enabler plugin activated, it starts capturing HTML before Flying Scripts (since ‘C’ starts before ‘F’ in plugins order). So it creates conflicts!

We need a single solution that will take care of everything, without creating conflicts, without eating too many resources, without needing a speed optimization expert.

What is FlyingPress

FlyingPress is an all in one solution to WordPress sites that take care of everything. From page caching, CDN to image optimization.

Any non-techie should be able to create super-fast WordPress sites without going to too many tutorials or multiple plugins for speed optimization.

It should automate all possible optimizations so that users don’t have many headaches.

How FlyingPress Optimize for Core Web Vitals

FlyingPress from the ground up was for a better user experience. We entirely wrote critical css generation and other libraries from scratch to get the best performance.

Both WP Rocket and LiteSpeed cache generate critical css. But I was never happy with their results.

Here is the comparison of core web vital metrics in my blog (wpspeedmatters.com) using different cache plugins:

WP Rocket:

wp rocket cls

LiteSpeed Cache:

litespeed cache cls

FlyingPress:

flying press

If you carefully look at the screenshots generated, you’ll notice a few things:

  • No layout shifts – As you can see in the screenshots, FlyingPress from the second frame itself rendered with any layout shifts. Avoiding such layout shifts helps in reducing Cumulative Layout Shifts.
  • Fast rendering – While WP Rocket and LiteSpeed cache displayed the blog post imagine 6th frame, FlyingPress showed it from the second frame itself, without even need of placeholder. FlyingPress uses several techniques like preloading above fold images, exclude above fold images from lazy loading, use native lazy load, our own super-fast JS lazy load lib etc. All of such optimizations helps in reducing First Contentful Paint and Largest Contentful paint.

FlyingCDN – Optimizations on the fly!

We already offload 90% of the optimizations externally. By enabling FlyingCDN, you can offload CSS/JS minify and image optimization to CDN.

Here are some of the features:

flying cdn features

Cloudflare vs FlyingCDN

Cloudflare is a CDN + proxy. FlyingCDN is just a CDN. So FlyingCDN is not an alternative to Cloudflare. You can use Cloudflare along with FlyingCDN.

FlyingCDN provides many features that are currently not available in Cloudflare or are very costly. 

One example is geo-replication. It will replicate files across different regions so that there will be very low latency even for uncached files.

Here is a comparison of FlyingCDN and Cloudflare features:

CloudflareFlyingCDN
Bandwidth pricingFree$3/100GB
Geo-replication❌✔
Nearest PoP routingBusiness plan ($200/m)✔
Image compressionPro plan ($20/m)✔
WebP conversionPro plan ($20/m)✔
Resized images for mobileBusiness plan ($200/m)✔

Why no Unlimited plan or LTD

Many of the paid plugins in the WordPress ecosystem provide an unlimited plan and sometimes LTD (lifetime deals) too.

I’m not against unlimited plans or LTD. It works great for some products, and I’ve even run LTD my previous startup.

However, it’s not possible in FlyingPress.

As I’ve mentioned before, FlyingPress is not just a plugin. We do many resource-intensive tasks, like removing unused css at our Google Cloud server cluster. So our server costs are pretty high. Unlimited plans or LTD is too risky.

We also wanted to prevent abuse by using the same account by multiple persons.

Similar case for LTD, it helps us to make quick money. But will put the business at risk in the long term. I want FlyingPress to be a sustainable business.

More than 100 websites? Contact us for custom pricing.

We’re not stopping here.

We’re still not close by the goal of delivering HTML pages from edge servers with <30ms latency worldwide, no matter which hosting you’re in or where is your server location. Our TTFB Optimizer is a work in progress and will be a game-changer in WordPress.

We’ve only set up the basement.

]]>
https://wpspeedmatters.com/why-i-built-flyingpress/feed/ 26
Dear WordPress Plugin/Theme Devs, You Don’t Need jQuery! https://wpspeedmatters.com/jquery-performance/ https://wpspeedmatters.com/jquery-performance/#comments Mon, 27 Jul 2020 05:22:03 +0000 https://wpspeedmatters.com/?p=3731 When I started coding in JavaScript back in 2013’s, I thought jQuery is the actual “JavaScript” and jQuery should be included in every page to execute my JS code.

But why? Because every code I copied from StackOverflow worked only after importing jQuery! 😅

What’s wrong with jQuery

jQuery is 90 KB, but when minified it’s only 32 KB.

That’s so small. A good CDN can deliver it in less than 50ms!

But it’s not about the size. jQuery has around 10k lines of code. You might not be using even 10% of it.

image 8

Every line has to be parsed and evaluated by the browser which is resource-intensive. This process affects render time, especially in mobile.

To see the actual difference, here is the same functionality written in pure jQuery and vanilla JavaScript:

jQuery:

<body>
  <div id="hello-div"></div>
  <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
  <script>
    // jQuery
    const div = $("#hello-div");

    for (let i = 0; i < 10000; i += 1) {
      div.append("<p>Hello world</p>");
    }
  </script>
</body>

Vanilla JavaScript:

<body>
  <div id="hello-div"></div>
  <script>
    // Pure JavaScript
    const div = document.getElementById("hello-div");

    for (let i = 0; i < 10000; i += 1) {
      const p = document.createElement("p");
      p.textContent = "Hello world";
      div.appendChild(p);
    }
  </script>
</body>

Here is the performance difference:

image 6
jQuery
image 7
Vanilla JavaScript

While jQuery took 2.4s, pure JavaScript only took 0.8s. That shows vanilla JavaScript is 4x faster than jQuery.

Why you don’t need jQuery

A few years back writing standard functions in vanilla JavaScript was pain and jQuery made our lives easier.

But web browsers have evolved a lot. Most of the functions that you wrote in jQuery can be written in pure JavaScript.

Here are a few examples:

1. Ajax Requests

Fetching data from a URL:

jQuery:

$.ajax({
  url: '/api.json',
  type: 'GET'
  success: (data) => {
    console.log(data)
  }
})

Vanilla JavaScript:

fetch('/api.json')
  .then(response => response.text())
  .then(body => console.log(body))

2. Find Elements & Manipulate

Find some elements from DOM (HTML) and change color:

jQuery:

<p><span>Hello</span>, how are you?</p>
<p>Me? I'm <span>good</span>.</p>

<script>
  $("p").find("span").css("color", "red");
</script>

Vanilla JavaScript:

<p><span>Hello</span>, how are you?</p>
<p>Me? I'm <span>good</span>.</p>

<script>
  document
    .querySelectorAll("p > span")
    .forEach((elem) => (elem.style.color = "red"));
</script>

3. Show/Hide Elements

Common use case of jQuery, show/hide something on click:

jQuery:

<button id="button">
  Hide me
</button>

<script>
  $("#button").click(function () {
    $("#button").hide();
  });
</script>

Vanilla JavaScript:

<button id="button">
  Hide me
</button>

<script>
  document.getElementById("button").addEventListener("click", function () {
    document.getElementById("button").style.display = "none";
  });
</script>

4. Animate

jQuery:

<button id="button" class="animate">
  Hide me
</button>

<script>
  $("#button").click(function () {
    $("#button").hide("slow");
  });
</script>

Vanilla JavaScript:

<style>
  .animate {
    opacity: 0;
    transition: opacity 0.5s ease;
  }
</style>

<button id="button">
  Hide me
</button>

<script>
  document.getElementById("button").addEventListener("click", function () {
    document.getElementById("button").classList.add("animate");
  });
</script>

You can find a lot more similar examples in:

What about Browser Support?

Most of the functions I used above are widely supported in all major browser.

It’s usually Internet Explorer and Opera Mini which doesn’t support some of them.

If you still want to support such old browsers, you can detect the browser and add polyfills. Here are a few polyfills for such common functions:

Browser support for querySelector:

image 1

Browser support for fetch:

image 2

Everyone is moving away, except WordPress

Thanks to advancement made in front-end development tools and browser support, we’re now able to drop jQuery as a dependency, but you’d never notice otherwise

Bootsrap 5 – blog post

GitHub.com also removed jQuery in 2018 – Removing jQuery from GitHub.com frontend.

While everyone has started moving away from jQuery, it’s pretty tricky in WordPress due to the vast number of plugins and themes.

From the recent blog post of Updating jQuery version shipped with WordPress:

image

WordPress should deprecate jQuery and gradually migrate to vanilla JavaScript.

You might not need JavaScript too

As I said before, the web and JavaScript is evolving fast. Similarly CSS.

Many functions which were done via JavaScript be done via CSS now. This gives another performance boost.

Some of them which can be done in pure CSS:

]]>
https://wpspeedmatters.com/jquery-performance/feed/ 3
How to Speed up HTTP to HTTPS Redirection in WordPress https://wpspeedmatters.com/http-to-https-redirection/ https://wpspeedmatters.com/http-to-https-redirection/#comments Sat, 27 Jun 2020 03:08:59 +0000 https://wpspeedmatters.com/?p=3674 If most of your visitors are from Google (organic) or social media sites, most probably they are directly visiting the HTTPS version.

But what if there are visitors who directly visit your site entering the domain in the browser?

In my case, I usually type “wps”, Chrome suggests “wpspeedmatters.com” and I press enter.

Browser by default sends the request to “http://wpspeedmatters.com” and later redirects to “https://wpspeedmatters.com”.

Why HTTP to HTTPS is slow?

If you’ve set up https in your WordPress settings, then WP will take care of the redirection.

But it will be done by PHP.

Depending on your hosting provider and load, redirection via PHP can be slow. It’s better to offload it from PHP.

Step1: Configure Web Server for HTTPS redirection

Configuring web server like Nginx/Apache/LiteSpeed to do the redirection will be always faster than PHP.

Apache/LiteSpeed

If you’ve Apache/LiteSpeed web server, add the following code to .htaccess file:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Nginx

In Nginx, add the following config:

server {
  listen 80;
  server_name domain.com www.domain.com;
  return 301 https://domain.com$request_uri;
}

Cloudflare

If you’re using Cloudflare, things are much easy. Go to SSL/TLS settings -> Edge Certificates and enable ‘Always Use HTTPS’.

image 2

Optionally, enable ‘Automatic HTTPS Rewrites’.

image 3

Additional Tip

You can also add a meta tag to tell the browser to use HTTPS for all requests inside a page.

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

Step 2: Enable HSTS

HSTS or HTTP Strict Transport Security is a response header.

In simple words, this tells the browser “hey, this website will have HTTPS for X no. days, so use HTTPS by default”.

So next time when someone enters “wpspeedmatters.com” or “http://wpspeedmatters.com”, browser directly opens “https://wpspeedmatters.com”.

HSTS has some security benefits too, MitM attack (Man in the Middle attack).

Apache/LiteSpeed

Add the following code to .htaccess file:

<IfModule mod_headers.c>
Header set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
</IfModule>

Nginx

In Nginx, add the following config:

server {
    listen 443 ssl;

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
}

Cloudflare

Under SSL/TLS settings -> Edge Certificates and Enable HSTS.

image 4

Configure it as below:

image 5

Verify HSTS

You can check if it’s working or not by checking the response header:

image

You can also visit https://hstspreload.org/ to check the same.

Step 3: Submit to Chrome HSTS List

Even if you’ve enabled HSTS, the user visiting your site for the first time will have HTTP to HTTPS redirection.

But Chrome maintains a list of HSTS enabled sites hardcoded in the browser (other browsers also use this list). So if your site is added to that list, no more redirection!

Go to https://hstspreload.org/ and submit your domain.

image 6

Conclusion

I’ve often seen redirection take ~1s in some shared hosting providers. This can affect your FCP, FMP etc.

We often test HTTPS version in testing tools like GTmetrix, Google PageSpeed Insights. But users who directly visiting our site may be from HTTP.

In my case, ~30% of the visitors are ‘direct’.

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

]]>
https://wpspeedmatters.com/http-to-https-redirection/feed/ 3
A-Z of Google Fonts Optimization in WordPress https://wpspeedmatters.com/optimize-google-fonts/ https://wpspeedmatters.com/optimize-google-fonts/#comments Sat, 23 May 2020 10:53:49 +0000 https://wpspeedmatters.com/?p=3509

The award for the page that requests the most web fonts goes to a site that made 718 web font requests!

Web Almanac

Yes, some designers/developers are lazy and add every possible font they can to make the site look good.

But what about performance?

Just like any other optimization, fonts need a high priority since the text is probably the first thing user see in a website.

This guide will show you different methods to optimize Google Fonts, especially for WordPress.

Use System Fonts Instead

Have you noticed that fonts in Medium.com, WordPress admin, GitHub loads so fast?

Well, all of them use system fonts.

/* System Fonts as used by GitHub */
body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}
/* System Fonts as used by Medium and WordPress */
body {
  font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",sans-serif;
}

System fonts are fonts preinstalled in every OS. Your browser doesn’t need to make extra HTTP requests to download stylesheets or font files.

Yes, zero requests!

The below text is rendered in system font:

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Not bad right? 😏

You won’t have a lot of choices in design, but if you want the best performance, go for it!

Limit Font Families & Weights

There are several optimizations that I’ve mentioned below. But limiting font families is the most important one. Ideally, you shouldn’t have more than 2 (max 3) font families.

Similarly, each font will have different weights. It starts from 100 to 900. Including each weight will result in an additional font file to download. So limit the number of font weights too.

If you’re directly embedding font from Google Fonts, you can select different weights like this:

image 1

Here is an example of choosing font families and weights in Oxygen:

oxygen google fonts setting

Credits: WPDevDesign

Use Variable Fonts (New!)

As I mentioned above, for each font-weight, the browser needs to download separate font files. So if you include 400 and 700, two font files will be downloaded.

But in variables fonts, a single font itself can transform into any font weight.

Here is a demo (try changing the font-weight):

Read more about variable fonts: https://web.dev/variable-fonts/.

You can filter fonts in Google Fonts that support variable fonts:

image 4

To give you a better understanding, here is the difference:

Font family, weight(s)Normal font sizeVariable font size
Roboto, 40016 KB20 KB
Roboto, 400 + 70030 KB35 KB
Roboto, 400 + 700 + 90043 KB35 KB
Roboto, 300 + 400 + 700 + 90057 KB35 KB
Roboto, 100 + 300 + 400 + 700 + 90059 KB35 KB

Here is a sample of variable font with weights from 100 to 900:

<link href="https://fonts.googleapis.com/css2?family=Roboto+Slab:wght@100..900" rel="stylesheet" />

Combine Google Fonts

Combining Google Fonts will reduce HTTP requests. It won’t have a big impact in performance with http/2. But still, a good practice to consider.

Before combining:

<link href="https://fonts.googleapis.com/css2?family=Open+Sans" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Roboto" rel="stylesheet">

After combining:

<link href="https://fonts.googleapis.com/css2?family=Open+Sans&family=Roboto" rel="stylesheet">

If you’re using FlyingPress turn on “Optimize Google Fonts” and it’ll take care of this optimization.

Fix Flash of Invisible Text

If you’re analyzed your site using Google PageSpeed Insights, you might have seen this error “Ensure text remains visible during webfont load”

fonts error goole psi

There is a font-display CSS property which tells whether to show a fallback font while loading the font or make the font completely invisible. If the user is on a slow connection and you haven’t enabled fallback, the user might not see the text for some time, also called Flash of Invisible Text (FOIT).

In Google Fonts, adding “&display=swap” at the end of the URL will fix this issue.

Before adding swap:

<link href="https://fonts.googleapis.com/css2?family=Roboto" rel="stylesheet">

After adding swap:

<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">

FlyingPress can fix this issue automatically. I’ve also developed a standalone plugin for this: Swap Google Fonts Display.

Load Google Fonts Asynchronously

Shall browser wait till CSS and its fonts files are ready to render the page? In my opinion, Google Fonts shouldn’t be render-blocking since a fallback font can be displayed meanwhile.

Lets load Google Fonts asynchronously. Add the following code to <head>:

<link rel="preload" href="https://fonts.googleapis.com/css2?family=Roboto" as="style" onload="this.rel='stylesheet'">

This tells the browser to preload Google Font in the background (without render-blocking) and makes it available as a stylesheet when ready.

Inline Google Fonts

There are different file formats for fonts, like ttf, otf, woff, woff2 etc. Google Fonts CDN is pretty intelligent to deliver different font files based on the user’s device.

But if you only want to support modern browsers, instead of linking to the stylesheet, directly inline the css contents.

The latest font format “woff2” is generally supported (except IE and Opera Mini). It will also have the lowest file size.

image 3

Before:

<link href="https://fonts.googleapis.com/css2?family=Roboto" rel="stylesheet">

After (unminified):

<style>
/* cyrillic-ext */
@font-face {
  font-family: 'Roboto';
  font-style: normal;
  font-weight: 400;
  src: local('Roboto'), local('Roboto-Regular'), url(https://fonts.gstatic.com/s/roboto/v20/KFOmCnqEu92Fr1Mu72xKKTU1Kvnz.woff2) format('woff2');
  unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
....
</style>

This way your browser can reduce a HTTP chain and download the font file immediately.

Add Resource Hints

If you closely look at a Google Font CSS, the stylesheet is downloaded from “https://fonts.googleapis.com/”. However, after downloading the CSS file, each font files are download from “https://fonts.gstatic.com”.

The browser needs to make another DNS lookup after downloading the stylesheet. This can add a slight delay.

By adding resource hints, we can tell the browser that “I’m going to connect to this URL shortly, so make it ready 😉”.

before preconnect
Before preconnect
after preconnect
After preconnect

Add the following line to <head>:

<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />

Or using Pre* Party Resource Hints plugin:

image 2

Self Host Google Fonts

But why self-host? Google Fonts are delivered from their super fast CDNs and it might have already been cached in the browser, right?!

  • The browser cache time for stylesheets is only 24 hours and 1 year for font files.
  • Even though fonts are delivered from their CDN, there involves two additional DNS lookups and multiple chained HTTP requests.
  • Browsers have started to implement double-key caching. Which means if website A downloads a font and cache it, it will not be available for website B. Safari has already implemented this. Chrome is about to ship. You can read more about it here.
  • Self-hosting can leverage your existing connection (http/2).

So it’s always better to self-host Google Fonts!

without self host
Before self-hosting
self hosting
After self-Hosting

How to self host Google Fonts in WordPress?

OMGF plugin can self-host Google Fonts. But I found it hard to use. We’ve to manually search the fonts or auto-detect by opening pages.

If you’re using FlyingPress, turn on “Optimize Google Fonts”. It will take care of self-hosting, combining and everything for you!

5 font 1

Conclusion

In the overall web, Google Fonts dominates by the usage of 75%. They’ve put the best effort to optimize them. But that doesn’t mean there is no more room to optimize.

Many of the optimizations can be easily done by installing FlyingPress like self-hosting, preloading, fallback font, combine, load async etc. But no plugin will be able to optimize your design choices.

Add the fonts that you really need, filter out unnecessary font weights and if possible, self host them.

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

]]>
https://wpspeedmatters.com/optimize-google-fonts/feed/ 6
How to use BunnyCDN for ShortPixel Adaptive Images https://wpspeedmatters.com/bunnycdn-for-shortpixel-adaptive-images/ https://wpspeedmatters.com/bunnycdn-for-shortpixel-adaptive-images/#comments Tue, 14 Apr 2020 01:23:00 +0000 https://wpspeedmatters.com/?p=3541 ShortPixel Adaptive Images uses its own CDN which doesn’t provide consistent performance. This guide will tell you how to configure BunnyCDN for ShortPixel Adaptive Images.

What is ShortPixel?

ShortPixel is an image compression service/plugin. It compresses all your images in WordPress media automatically, with best the best quality to compression ratio.

What is ShortPixel Adaptive Images?

While ShortPixel only compresses images, ShortPixel Adaptive Images compress images, resize and deliver them as WebP on the fly from their own CDN.

Why BunnyCDN?

One of the fastest CDN with 37+ pops and extremely cheap!

You can read my review and comparison here:

Configure BunnyCDN for ShortPixel Adaptive Images

Create an account in BunnyCDN if you haven’t created yet.

Go to ‘Pull Zones’ and create a new one.

image 1

In the host name, enter the name you want. In the Origin URL enter “https://no-cdn.shortpixel.ai/”.

Now go to your ShortPixel Adaptive Images settings -> Advanced.

In the API URL, enter name your put in the following format:

image 3

Done! Your images will now be served via BunnyCDN + ShortPixel Adaptive Images!

You can also add your own custom subdomain to BunnyCDN (optional).

image

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

]]>
https://wpspeedmatters.com/bunnycdn-for-shortpixel-adaptive-images/feed/ 4
Faster and Better Search Results with Algolia in WordPress https://wpspeedmatters.com/algolia-search-in-wordpress/ https://wpspeedmatters.com/algolia-search-in-wordpress/#comments Mon, 02 Mar 2020 13:54:28 +0000 https://wpspeedmatters.com/?p=3470 I recently enabled ‘Site search Tracking’ in Google Analytics to see what people are searching in my blog.

Screenshot 2020 03 02 at 12.48.17 PM

The results were quite interesting. A good percentage of the search keywords has typos which resulted in Zero search results!

Here are a few examples:

Screenshot 2020 03 04 at 10.36.40 AM 1

So I researched a lot and ended up using Algolia.

What is Algolia?

Algolia is a “Search as a service”. You provide them with the content and they provide you with an API for search.

Why Algolia in WordPress?

  • Offload WordPress search – Every time you search for a keyword in default WordPress, the keyword is searched in the MySQL table which is a resource-intensive task, especially if there are a lot of posts.
  • Faster search results (extremely fast) – As I mentioned above, the default search is resource-intensive and can quickly become slow on large sites. Algolia can get results in <5ms!
  • Better user experience – Auto suggestions, typo tolerant, instant results, highlight keyword and much more.

Here is how my search results look like before and after when user types “buny” (meant “bunny” or “BunnyCDN“)

Screenshot 2020 03 02 at 4.04.57 PM
Before
Screenshot 2020 03 02 at 4.06.48 PM
After

Pricing of Algolia

image

You can find the detailed pricing here.

The free plan says “for personal, non-commercial projects”. My blog is commercial, so I contacted their support to see if I can use the free plan.

Here is what they said: “The free plan is for non-commercial use but it’s more a legal term than anything. You can use the free plan as long as you display the Algolia logo in the search results page“.

How to Implement Algolia Search in WordPress

Get Algolia API keys

Sign up for Algolia and get the API keys (an app will be automatically created).

image 1

Install and Configure WordPress plugin

Install WP Search with Algolia and add the above API keys in the plugin settings

image 2

Configure Search Page

By default, it will be set to “Do not use Algolia”. Choose “Use Algolia in the backend” or “Use Algolia with Instantsearch.js”.

image 3

Algolia in the backend vs Instantsearch.js

I use “backend” options in this blog, mainly because it plays nicely with my theme and doesn’t inject any JavaScript.

Here is the difference:

BackendInstantsearch.js
Search interfaceFrom ThemeAlgolia UI
Algolia logoAdd via custom codeEnable/disable from the plugin
Typo tolerant✅✅
Instant results❌✅
Autocomplete❌✅
Extra JS file❌✅

Conclusion

Implementing Algolia is not just about getting faster results, it’s about providing better user experience. I regret I didn’t do this earlier!

Are you planning to use Algolia? Let me know.

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

]]>
https://wpspeedmatters.com/algolia-search-in-wordpress/feed/ 7