How to Delay The Execution of JavaScript to Boost Page Speed

How to Delay JavaScript to Boost Page Speed

In recent years, approaching users on multiple channels such as advertising websites, social networks, or live chat services has become more and more popular. And then, using scripts to insert those services into a website is the most important technique. However, using too many 3rd party scripts will cause a slower loading speed of the website and its Page Speed scores may be worse. At that time, you often have just 2 options: accept the slow loading or remove some scripts. After a while of researching, we found a way to have one more option. It’s delaying the execution or loading of JavaScript. Let's see how!

Why delaying JavaScript?

Data downloaded from third-party servers like Facebook Page Widget, Facebook Messenger, Facebook Comments, iframe or live chat services like Tawk.to are data that you cannot control. You cannot compress, merge or cache them, simply because they are not on your host. These data are often very heavy and can cause serious problems related to website loading speed. To see this clearly, you can use Google PageSpeed ​​Insights, GTmetrix, or any other speed test tools to verify.

And since you cannot optimize them, the only solution to integrate the above services into the website without affecting the page speed is to delay the execution of their scripts. In this way, you will reduce your page render time and improve speed indexes on page speed testing tools such as Time to Interactive, First CPU Idle, Max Potential Input Delay, etc. This will also reduce the initial payload on the browser by reducing the number of requests.

Note: This technique is based on the code of Flying Scripts, which allows you to delay scripts in WordPress. The plugin has more control options in the admin area where you don't need to touch code. So, check it out if you want that. Otherwise, let's discover how the code works below.

How to delay JavaScript in WordPress

The delay script

To delay scripts, we need to write a custom code. This code is called "delay script" and its job is delaying other scripts. In other words, it's used to load other scripts on the website.

You can put this script in the <head> or <body> tag. But you should put it in the <head> tag to run it at the same time with the lazy load scripts. It is more reasonable for most cases. If the delayed scripts are in the <head> tag, they will not work when placed in the <body> tag because the script will be loaded just after the whole page finished loading.

<script>
{
    const load = () => {
        document.querySelectorAll("script[data-type='lazy']").forEach(el => el.setAttribute("src", el.getAttribute("data-src")));
        document.querySelectorAll("iframe[data-type='lazy']").forEach(el => el.setAttribute("src", el.getAttribute("data-src")));
    }
    const timer = setTimeout(load, 5000);
    const trigger = () => {
        load();
        clearTimeout(timer);
    }
    const events = ["mouseover","keydown","touchmove","touchstart"];
    events.forEach(e => window.addEventListener(e, trigger, {passive: true, once: true}));
}
</script>

Note: You can use the Slim SEO plugin to to add code to the header. This plugin allows you to insert any code to the header, body, or footer. So you can use it to insert Webmaster tool verification codes or tracking scripts.

Because there will still be scripts you want to execute right away, the above script doesn’t delay the execution of all the scripts on your site. In there, I specified that only scripts with the attribute data-type='lazy' (you can rename the attribute freely) will be delayed. Therefore, after adding the above script, you need to find all the scripts that you want to delay to add this attribute. I will do this in the next step.

The above script also specifies that it will delay the execution of the specified scripts until one of the following two conditions occurs:

  1. The user interacts on the website, such as scrolling the screen, typing from the keyboard, or touching from mobile devices.
  2. After a certain time specified by you, in the above code - 5s, the script will still be executed even if there is no user interaction.

Modify existing scripts

After adding the delay script, we need to modify exising scripts on your website to make them delayed. For each type of script, there will be a different way to do that. Here is how to do it for some popular scripts like Google Tag Manager, Facebook Customer Chat, Youtube, or Google Maps.

Google Tag Manager

Below is the default Google Tag Manager script:

<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','YOUR-GTM-ID');</script>

You can rewrite it with the delay script as follows:

<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({'gtm.start': new Date().getTime(), event: 'gtm.js'});
</script>
<script data-type="lazy" data-src="https://www.googletagmanager.com/gtm.js?id=YOUR-GTM-ID"></script>

Google Analytics

The default Google Analytics code looks like this:

<script async src="https://www.googletagmanager.com/gtag/js?id=YOUR-ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', 'YOUR-ID');
</script>

To delay it, change it to:

<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'YOUR-ID');
</script>
<script data-type="lazy" data-src="https://www.googletagmanager.com/gtag/js?id=YOUR-ID"></script>

Facebook Customer Chat

Here is the default Facebook script, used to load the Customer Chat widget:

<div id="fb-root"></div>
<div id="fb-customer-chat" class="fb-customerchat"></div>
<script>
    var chatbox = document.getElementById('fb-customer-chat');
    chatbox.setAttribute("page_id", "YOUR_PAGE_ID");
    chatbox.setAttribute("attribution", "biz_inbox");

    window.fbAsyncInit = function() {
        FB.init({
            xfbml : true,
            version : 'v12.0'
        });
    };

    (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = 'https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js';
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
</script>

In it, the code is in the paragraph (function()...); used to load chat widgets to your website.

I will shorten it by removing the function() code and adding a script like this right below the the code as follows:

<script data-type='lazy' data-src="https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js"></script>

Then, the code of Facebook Customer Chat will look like this:

<div id="fb-root"></div>
<div id="fb-customer-chat" class="fb-customerchat"></div>
<script>
    var chatbox = document.getElementById('fb-customer-chat');
    chatbox.setAttribute("page_id", "YOUR_PAGE_ID");
    chatbox.setAttribute("attribution", "biz_inbox");

    window.fbAsyncInit = function() {
        FB.init({
            xfbml : true,
            version : 'v12.0'
        });
    };
</script>
<script data-type='lazy' data-src="https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js"></script>

If you use another plugin of Facebook such as Facebook Comment, Facebook Widget, or other live chat services such as Tawk.to, you can do likewise.

Youtube

Youtube and Google Maps use iFrame tags. With this tag, you just have to add data-type='lazy' and data-src like this:

The default of Youtube is:

<iframe src="https://www.youtube.com/embed/I3ncHxLxwlM"></iframe>

Now, I will change it into this:

<iframe data-type='lazy' data-src="https://www.youtube.com/embed/I3ncHxLxwlM"></iframe>

Google Maps

The default iFrame of Google Maps is:

<iframe src="https://www.google.com/maps/embed/v1/place?key=API_KEY&q=Space+Needle,Seattle+WA"></iframe>

So I will change it by adding data- type='lazy' inside the tag <iframe> like this:

<iframe data-type='lazy' data-src="https://www.google.com/maps/embed/v1/place?key=API_KEY&q=Space+Needle,Seattle+WA"></iframe>

Other Scripts

If you want to apply this method to the common scripts, you just need to replace src into data-src and add the data-type='lazy' attribute.

An example is:

<script src="custom-javascript.js"></script>

Then, change it into this:

<script data-src="custom-javascript.js" data-type='lazy'></script>

Should (not) you delay scripts?

This technique should be used for scripts related to the user interaction or live chat like Facebook Customer Chat, Facebook Widget, Facebook Comment, iframe (Youtube, Google Maps), Tawk.to, …

Otherwise, it isn’t recommended for scripts like tracking or analyzing user data such as Google Analytics, Facebook Pixel, Google Tag Manager, Crazy Egg, Google Remarketing Tag, ... Because applying this technique may cause recording data incompletely or inaccurately. You certainly won't want to miss this data, right?

However, even in the case you use tracking scripts, you still want to delay them, to increase the performance of the website. That will give you a better pagespeed score, better Core Web Vitals and as they're a ranking factor, it might help you rank better on Google.

Last words

Delaying the script execution method will help you optimize your website’s loading and increase page speed scores as well. There are many ways to increase the speed of websites; so, consider what is more suitable for you to use. If you cannot apply this method to your websites, you can read about other methods in this series.

If you have any questions, feel free to let us know in the comment section. Good luck!

Gutenberg vs Page Builders - What is Better and Faster? In-depth Comparison

Gutenberg vs. Page Builders - What is Better & Faster? In-depth Comparison

You can build a website with WordPress without much coding skill, or even without touching any line of code. The reason lies in many wonderful tools which help you do it easily. The most popular tools, it’s no doubt to say, are Gutenberg and page builders. At the moment, they have their pros and cons, so it’s not easy to decide which one is the best and overwhelms the other.

Continue reading "Gutenberg vs. Page Builders - What is Better & Faster? In-depth Comparison"

How to Test a Plugin's Performance and Security

How to Test a Plugin's Performance and Security

Plugins can bring many advantages to your WordPress website. However, you should consider carefully before using one because it may contain viruses and malicious codes. They also may affect your website loading speed/performance. To check if a plugin has an issue, especially for a newly launched plugin, you can use various useful tools and follow the steps below.

Continue reading "How to Test a Plugin's Performance and Security"

How to configure WP Rocket plugin to maximize speed

How to Configure WP Rocket Plugin to Maximize Speed

Since search engines place so much significance on the speed of the loading time, it became vital to maximizing the website’s speed. Improving your website’s speed brings along a lot of benefits. Faster websites prove to have better conversions, higher search engine rankings, and further content reach. Another problem with slow loading time is that visitors instantly abandon pages that don’t load within a few seconds after opening!

Continue reading "How to Configure WP Rocket Plugin to Maximize Speed"

The Fastest Way To Load Google Fonts In WordPress (Part 2)

The Fastest Way To Load Google Fonts In WordPress (Part 2)

Google Fonts is always a bottleneck for website performance. The Google Fonts' CSS is a render-blocking resource, which means that the browser won't render any processed content until the CSS is loaded. It also causes a blank space when the font is being loaded.

In the previous post of this series, I have shown you a way to get rid of these problems using a script from PerfPerfPerf. Since then, Google Fonts has some updates and the PerfPerfPerf's becomes outdated. And we need a better way to load Google Fonts now!

Google Fonts loading problems

Before going into the solution, let's summarize 2 issues, as they are the most important problems with Google Fonts. And these are the problems we're going to resolve in this article.

Google Fonts Render Blocking CSS

When Google Fonts is being loaded, no further content (text, images, CSS, JavaScript, etc.) is loaded. That means your whole page is blocked until Google Fonts finishes loading its CSS.

This problem is critical because it freezes your website when loading and increases the First Contentful Paint (FCP) of the page. FCP is an important, user-centric metric for measuring perceived load speed because it marks the first point in the page load timeline where the user can see anything on the screen—a fast FCP helps reassure the user that something is happening. It's a part of the Web Core Vitals and is an SEO factor. So if you have it high, your site might get a lower ranking.

Blank space while loading Google Fonts

The FOIT (Flash Of Invisible Text) effect that causes bad user experience and bad FCP (First Contentful Paint)
The FOIT (Flash Of Invisible Text) effect that causes bad user experience and bad FCP (First Contentful Paint)

Another problem with Google Fonts is that when it's being loaded, the text is completely vanished before your eyes. Only until it's finished loading, you can see the text. This effect is called FOIT (Flash Of Invisible Text).

That causes a really bad experience for your users. And if the loading time is huge, your users might think your website is broken (because they see nothing!).

And FOIT also affects the First Contentful Paint (FCP) as well, and thus might affect your search ranking.

How to fix Google Fonts problems

Load Google Fonts asynchronously

To solve the 1st problem of render-blocking, we need to load Google Fonts asynchronously. That means we'll load the Google Fonts' CSS without blocking loading or rendering other resources.

There are 2 solutions:

Preloading CSS with rel="preload"

preload is a mechanism to load resources without any effect on loading the other ones. It also puts a higher priority on the resources that are preloaded. That means these resources will be load before other resources. You can read more about this on MDN.

Let's assume you want to load Roboto font. Google gives you the HTML like this:

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

To make the CSS preloaded, you need to change it to:

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

The CSS is now preloaded. And when it finishes loading, it'll be applied.

The preload technique works well in all modern browsers.

Using media type

Another solution is using media type, which is supported by all browsers. This technique is created by Filament Group. The HTML markup is simple as follows:

<link href="https://fonts.googleapis.com/css2?family=Roboto" rel="stylesheet" media="print" onload="this.media='all'">

What it does is loads the CSS for the print-based media. In other words, the CSS is applied only when the users try to print the page. The loading process is now asynchronous (since we're on browsers). And when it's done, the CSS is applied for all media (which includes browsers).

I've been testing this technique for a while and see a good improvement in font loading. You can test on MetaBox.io and docs.metabox.io websites to see how it works.

Using font-display: swap

To solve the 2nd problem with a blank is when loading fonts, we need to use font-display: swap. Basically, it allows us to display the text first with a fallback font family (usually serif or sans-serif). And when the font is loaded, it swaps the text into the wanted font. This effect is called FOUT (Flash Of Unstyled Text). Unlike FOIT (Flash Of Invisible Text), users still see the text while the font is loaded. So, the user experience is better. And also the FCP (First Contentful Paint) is lower.

The good news is Google Fonts now supports font-display: swap by default. You can see it in the font URL like this:

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

Notice the display=swap in the URL. The CSS loaded for the font will have font-display: swap.

This technique works in all modern browsers, and it's safe to use.

Just a note that the solution in the 1st part of this series, which uses PerfPerfPerf script, tries to add font-display: swap to the Google Fonts' CSS. It's not needed anymore.

So the final code to load Google fonts now is either of these:

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

Apply Google Fonts loading techniques in WordPress

The best way to apply the techniques above is adding the code into your theme's header.php file. Or you can create a child theme and modify the header.php file. So your header.php file will look like this:

<!doctype html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet" media="print" onload="this.media='all'">
    <?php wp_head(); ?>
</head>
// Other code

I find it's harder to do this if you use page builders. You need to disable default Google Fonts and apply the code above. The only plugin I found that disables the Google Fonts is Autoptimize. Unfortunately, it removes our manual link tag, too.

The best solution for page builders is using Autoptimize to preload the Google Fonts. You can turn it on the settings page:

Preload Google Fonts in WordPress with Autoptimize
Preload Google Fonts in WordPress with Autoptimize

You can see it in action on GretaThemes website.

Conclusion

After applying the new techniques to our websites, I'm quite happy with the result. The loading speed is increased and the FOUT effect is minimal. Users probably don't notice the font change (swapping). And of course, the Google PageSpeed Insights score is higher than before (in my test for MetaBox.io's homepage, it has 100 scores for desktops).

I think optimizing the loading speed for Google Fonts is very important for both users and search engines. And you should do it now. Feel free to discuss this with us on the Facebook group, or leave a comment below.

load google fonts wordpress

The Fastest Way To Load Google Fonts In WordPress!

Nowadays, except for system fonts, Google Fonts is the optimal option for most websites for typography. However, there will be 2 disadvantages when you load Google Fonts for typical websites as instructed by Google's tutorials, or by the way to enqueue CSS in most WordPress themes:

  1. The next resources (CSS, JS, images, ...) are blocked while loading fonts. You must wait for loading fonts completely, then these resources continue loading.
  2. The text using Google Fonts won’t display while loading, but it only shows a blank space.

The first drawback will make your website load slower. That'll make your Google PageSpeed Insights scores decrease, so does the SEO scores. The other will cause a bad user experience.

So, how do we solve these 2 weaknesses?

Note: the techniques in this post is outdated. Please visit the 2nd part of this series for a better method. The content in this post is still useful for reference.

How to optimize the Google Fonts loading

Our purpose is to deal with 2 above disadvantages while loading Google fonts, to be more specific:

  • The other resources must load normally, in order to make your website load faster.
  • The text must display as usual. When the font is loaded completely, the displayed text will use that font. That can cause a second flash when changing the font. However, this effect may be acceptable because it happens in the blink of an eye.

To do these two tasks at once, we will use the script Google Fonts provided by PerfPerfPerf. Follow up the below way:

Supposing that you need to load font Roboto into your website, we generally add the below script after the <head> section of the website (in a file header.php of the theme):

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

Or enqueue into the WordPress theme as follows ( functions.php ):

add_action( 'wp_enqueue_scripts', 'themeprefix_scripts' ); 
function themeprefix_scripts() { 
    wp_enqueue_script( 'themeprefix-fonts', themeprefix_fonts_url() ); 
} 
function themeprefix_fonts_url() { 
    return 'https://fonts.googleapis.com/css?family=Roboto'; 
}

Instead of doing so, now you only need to copy the URL of the font https://fonts.googleapis.com/css?family=Roboto and access PerfPerfPerf page, paste that URL into a URL fonts box. Then, copy the code in the text area box and paste that code into the<head> section of the website. Or if using WordPress, you can hook into wp_head as following (insert into the functions.php file of the theme):

add_action( 'wp_head', 'themeprefix_load_fonts' ); 
function themeprefix_load_fonts() { 
    ?> 
<!-- Code snippet to speed up Google Fonts rendering: googlefonts.3perf.com --> 
<link rel="dns-prefetch" href="https://fonts.gstatic.com"> 
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="anonymous"> 
<link rel="preload" href="https://fonts.googleapis.com/css?family=Roboto" as="fetch" crossorigin="anonymous"> 
<script type="text/javascript"> 
!function(e,n,t){"use strict";var o="https://fonts.googleapis.com/css?family=Roboto",r="__3perf_googleFontsStylesheet";function c(e){(n.head||n.body).appendChild(e)}function a(){var e=n.createElement("link");e.href=o,e.rel="stylesheet",c(e)}function f(e){if(!n.getElementById(r)){var t=n.createElement("style");t.id=r,c(t)}n.getElementById(r).innerHTML=e}e.FontFace&&e.FontFace.prototype.hasOwnProperty("display")?(t[r]&&f(t[r]),fetch(o).then(function(e){return e.text()}).then(function(e){return e.replace(/@font-face {/g,"@font-face{font-display:swap;")}).then(function(e){return t[r]=e}).then(f).catch(a)):a()}(window,document,localStorage); 
</script>
<!-- End of code snippet for Google Fonts -->
    <?php
}

After that, load your website again. You will see that the other resources still load normally while loading the font. And when the font is loaded completely, this text will use that font.

The working mechanism and browser compatibility

The reason why the script of PerfPerfPerf, which has just been created recently, can solve the above problems is dependent on several up-to-date technologies on the browsers.

The working mechanism of this script is quite simple but really efficient:

  • Using thepreload mechanism to load the font. This one allows the browser to priory load the underground resources without any effect on loading the other ones. Now, all browsers support strongly the preload.
  • Using thefont-display: swap mechanism to display the text first then load the font completely, turn the text's display into the wanted font. All browsers, except IE and Edge, support this attribute.

In case the browser doesn’t support one of or both mechanisms, the fonts will be loaded as usual and your website is still displayed as before.

Make a point of utilizingfont-display: swap, when you inform font in CSS, you must have fall-back font in the end, as follows:

h1, h2 { font-family: Roboto, sans-serif; }

Don't write as below:

h1, h2 { font-family: Roboto; }

How to load Google Fonts in WordPress themes

It will be a really suitable choice if you do it for your websites. But, for WordPress themes, there will need to get a little tweak.

Have a look at the below code which I used for the EightyDays theme of GretaThemes:

add_action( 'wp_head', 'themeprefix_load_fonts' ); 
function themeprefix_load_fonts() { 
    $url = themeprefix_fonts_url(); 
    ?> 
<link rel="dns-prefetch" href="https://fonts.gstatic.com"> 
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="anonymous"> 
<link rel="preload" href="<?php echo esc_url( $url ); ?>" as="fetch" crossorigin="anonymous"> 
<script type="text/javascript"> 
!function(e,n,t){"use strict";var o="<?php echo esc_url( $url ); ?>",r="__3perf_googleFontsStylesheet";function c(e){(n.head||n.body).appendChild(e)}function a(){var e=n.createElement("link");e.href=o,e.rel="stylesheet",c(e)}function f(e){if(!n.getElementById(r)){var t=n.createElement("style");t.id=r,c(t)}n.getElementById(r).innerHTML=e}e.FontFace&&e.FontFace.prototype.hasOwnProperty("display")?(t[r]&&f(t[r]),fetch(o).then(function(e){return e.text()}).then(function(e){return e.replace(/@font-face {/g,"@font-face{font-display:swap;")}).then(function(e){return t[r]=e}).then(f).catch(a)):a()}(window,document,localStorage); 
</script>
    <?php
} 
function themeprefix_fonts_url() { 
    $fonts = array(); 
    $subsets = 'latin-ext'; 
    /* translators: If there are characters in your language that are not supported by Crimson Text, translate this to 'off'. Do not translate into your own language. */ 
    if ( 'off' !== _x( 'on', 'Crimson Text font: on or off', 'themeprefix' ) ) { $fonts[] = 'Crimson Text:400,400i,700,700i'; } /* translators: If there are characters in your language that are not supported by Merriweather, translate this to 'off'. Do not translate into your own language. */ if ( 'off' !== _x( 'on', 'Merriweather font: on or off', 'themeprefix' ) ) { 
        $fonts[] = 'Merriweather:400,400i,700,700i'; 
    }

    /* translators: If there are characters in your language that are not supported by Merriweather, translate this to 'off'. Do not translate into your own language. */ 
    if ( 'off' !== _x( 'on', 'Merriweather font: on or off', 'themeprefix' ) ) { 
        $fonts[] = 'Merriweather:400,400i,700,700i'; 
    } 

    $fonts_url = add_query_arg( array( 
        'family' => rawurlencode( implode( '|', $fonts ) ), 
        'subset' => rawurlencode( $subsets ),
    ), 'https://fonts.googleapis.com/css' );

    return $fonts_url;
}

This code will do the following things:

  • Allow the users to choose both loaded fonts and subsets of their using language through the function. Doing this one by translating them from on to off (or maintain them) in the WordPress theme. If you don't know how to translate a WordPress theme to another language, refer to this article.
  • Generate the JavaScript code for fonts through function themeprefix_load_fonts. This script is copied from the above PerfPerfPerf page. It's using PHP here to change fonts URL only.

Pay attention that you must replace themeprefix with the slug of your theme.

How to deal with page builders plugins or WordPress themes that already load Google Fonts

Not always do you build a theme from scratch? Most people create their websites by using themes from some theme provider or page builder plugins as Beaver Builder or Elementor. In this situation, it will be very difficult to control how to load Google Fonts as well as apply the script provided by PerfPerfPerf.

However, don’t worry, there is still a method to solve this problem. Here takes GretaThemes website as a typical example. This site utilizes Beaver Builder and its available themes to build its web. Because of using the page builder plugin, selecting the font is very easy, with just a few mouse clicks. So, how to optimize Google Fonts loading?

Step 1: See which Google Fonts you are using

For this, you can view it in the theme which you are using, and in the enqueue style section. Pay attention that using page builders may cause it is impossible to get all the fonts like that. The easiest way to get all fonts is by pressing F12 when you are opening the website with Google Chrome or Firefox then see those fonts' URLs in the Network tab:

Load Google Fonts URL in browser dev tools
Get Google Fonts URL in-browser dev tools

Then, copy that URL and save it to use for the below step 3.

Step 2: Disable all Google Fonts loaded by theme and plugin

Next, you must disable all Google Fonts loaded by theme and plugin. You can dequeue CSS files which are enqueued by theme and plugin to get it. However, it takes a lot of time because you must know the IDs of these CSS files. Regarding themes, it is also easy, but it's quite complete if you use page builder.

In place of doing that way, we can use the Autoptimize plugin. This plugin allows us to disable all Google Fonts on the website. Just go to Settings → Autoptimize and select the Extra tab, then on Google Fonts section, select Remove Google Fonts.

Load Google Fonts For WordPress
Disable Google Fonts with Autoptimize

Step 3: Load Google Fonts into the website

After Google Fonts are disabled, we need to load Google fonts manually. I want you to copy the URL fonts you get in step 1, then access to PerfPerfPerf page, paste the URL fonts into this page to generate the script.

Then, insert that script into your website by adding the following code to the functions.php file of the theme (or child theme):

add_action( 'wp_head', 'themeprefix_load_fonts' ); 
function themeprefix_load_fonts() { 
    ?> 
<!-- Code snippet to speed up Google Fonts rendering: googlefonts.3perf.com --> 
<link rel="dns-prefetch" href="https://fonts.gstatic.com"> 
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="anonymous"> 
<link rel="preload" href="https://fonts.googleapis.com/css?family=Roboto" as="fetch" crossorigin="anonymous"> <script type="text/javascript"> !function(e,n,t){"use strict";var o="https://fonts.googleapis.com/css?family=Roboto",r="__3perf_googleFontsStylesheet";function c(e){(n.head||n.body).appendChild(e)}function a(){var e=n.createElement("link");e.href=o,e.rel="stylesheet",c(e)}function f(e){if(!n.getElementById(r)){var t=n.createElement("style");t.id=r,c(t)}n.getElementById(r).innerHTML=e}e.FontFace&&e.FontFace.prototype.hasOwnProperty("display")?(t[r]&&f(t[r]),fetch(o).then(function(e){return e.text()}).then(function(e){return e.replace(/@font-face {/g,"@font-face{font-display:swap;")}).then(function(e){return t[r]=e}).then(f).catch(a)):a()}(window,document,localStorage); 
</script> 
<!-- End of code snippet for Google Fonts --> 
    <?php 
}

Pay attention to changing the above script into the one which you copy on the PerfPerfPerf page.

If you don't want to code, you can use the Slim SEO plugin to insert that code. Go to Settings → Slim SEO, then paste that script:

Insert header and footer code with Slim SEO
Insert header and footer code with Slim SEO

Note that Slim SEO is a SEO plugin for WordPress. It supports inserting webmaster verification tags or tracking scripts into the header or footer of the website. We use it to insert our scripts to load Google Fonts. But Slim SEO does more than that. It's a free WordPress SEO plugin that's lightweight, fast and has no-bloat. It's developed by the same team at Meta Box, so check it out!

In case you use Beaver Theme, to simplify, you can go to Customize → Code → Head Code and directly paste that script from PerfPerfPerf to there:

Load Google Fonts For WordPress
Insert Google Fonts script in Beaver Builder

That's done!

So, we have learned about how to load Google Fonts faster for WordPress: do manually and by plugins. At the same time, we also see how to deal with the page builder plugins. With these methods, your website speed and user experience will increase significantly. So let’s get started it, apply immediately to your website, and let me know the results in the below comment section.

How to Speed up WordPress with Redis Caching

How to Speed up WordPress with Redis Caching

How to speed up WordPress using Redis cache is such a simple thing. Redis is an in-memory database that can be used as a data store or cache. Redis presents itself as an ideal solution to speeding up WordPress and any other software which supports Redis cache. In this article, we’re going to show you how to set up WordPress caching with Redis on a Linux VPS.

Continue reading "How to Speed up WordPress with Redis Caching"