Loading Google Fonts Locally: Start From The Top for Speed

Loading Google Fonts Locally: Start From The Top for Speed

Revolutionize your site’s speed with our guide on loading Google Fonts locally! Discover the secrets to faster performance, better privacy, and full control over your WordPress design. Say goodbye to slow load times and hello to a seamless user experience. Ready for a faster, smoother site? Let’s begin.

OPTIMIZING YOUR WEBSITE'S FONTS FOR SPEED

HOW TO LOAD “GOOGLE FONTS” LOCALLY ON WORDPRESS FROM THE FUNCTIONS FILE

If you're like most website owners, once you load your site, you'll want to enhance its performance based on your traffic reports. Consider improvements that can be made within your control to boost performance.

Serving fonts directly from your website's files, or loading google fonts locally, is one method to enhance load speed. WordPress platform users typically work with commercial themes and have access to a file called functions.php. Most themes use Google fonts.

Firstly, I'd like to recommend from the outset that any changes to your site should always be made within a WordPress “child theme”[1]. Secondly, it's good practice always to back up your site first.

This post will focus on Google Fonts, the most commonly used fonts for styling websites and applications (and they're free – woohoo!).

As developers and designers, here at boxoforganicfresh.com, we strongly advocate for loading Google fonts locally over serving them through Google's CDN (“Content Delivery Network”) for two reasons:

  1. Time and time again, we have tested them for speed, and local fonts always outperform.
  2. The conversation around privacy has become more prevalent, and the GDPR (“General Data Protection Regulation”)[2] has a significant impact on how websites protect their users, even in countries outside of the EU. The question is, does Google compromise the privacy we offer our users or expose us to potential legal arguments in the future?

Some people argue against loading Google fonts locally with outdated arguments. One popular argument is that designers lose the benefit of improvements Google might make to fonts. However, we maintain that this isn't a strong enough reason to make your site load slower, and that most likely only designers would notice any design improvements—To all others, popular fonts like Roboto or Times New Roman will probably continue to look the same.

Another outdated argument is that most web-developers and designers plan for their CDN execution, and most services like Hostinger, offer this service as a part of your hosting subscription.

In this comprehensive guide, we'll walk you through easy instructions for optimizing Google fonts and serving them locally—our goal is to boost site loading speed and avoid delays caused by render-blocking results that often occur when loading Google fonts from their host fonts.gstatic.com.

We were primarily motivated to share instructions once we developed our process because after months of researching “How to load Google fonts locally,” we found that most of the time, outdated or complicated instructions proved too technical to follow, were incomplete, skipped steps, or failed to achieve the desired results for our WordPress theme.

CONDITIONAL FOLLOW-ALONG INSTRUCTIONS:

You must have access to your server via FTP and a basic understanding of creating files, working with the WordPress functions.php file, and making alterations to your child theme. If you don't have any of these skills or access, send these instructions to someone who can help you.

As a startup or early business entrepreneur, you should know the basics of website design or development. Yes, leave the work to experts, but don't let yourself off from being capable of your overseeing your business. You can find basic concepts to learn how to have more control over your WordPress platform by clicking the links we provide you at the end.

We'll use our site to test and show the results of the following instructions. In transparency, you will find these files where they are supposed to be. If you inspect our web page, we are loading Google fonts locally where we state that they are.

You should not show information that appears in files that are PHP, for security reasons. We are doing so with caution to show how to load google fonts locally and so you have everything you need to customize this for your use. These instructions should improve your load time if you perform an exact copy example on your own test site.

Please note: We approached this article with an unaltered theme. Keep in mind that every theme is different. We provide workable solutions that should work with various well-built themes.

Please consult with your developer or theme designer if you encounter a problem we can't solve as a community.

If you do have a question that you can't find the answer to, consider buying us a cup of coffee when you sign up to comment. 🙂 It stimulates our team to answer promptly and motivates them to do so.

And definitely:

Please feel free to comment below if you have additional information to contribute, or suggestions for improving our instruction posts or if you discover any other improvements for loading Google fonts locally that you want to share.

SECTION 1: ORGANIZING YOUR LOCAL GOOGLE FONTS

STEP 1: SET UP YOUR FOLDER STRUCTURE

Let's begin by creating a well-organized folder structure for your website. We want to keep things simple and easy to follow. Instead of using confusing folder names like ‘fonts,' let's name them after your project. In our example, we'll use ‘BOX.'

Your file structure should look like this:

📁 BOX (top-level folder)

📁 box-fonts (a subfolder inside ‘BOX' for holding our fonts)

📃 box-fonts.css (our stylesheet in the ‘BOX' folder that tells the website where to find fonts in the ‘box-fonts' folder)

This structure makes it clear what's what.

STEP 2: WORKING WITH YOUR GOOGLE FONTS

Now, let's choose and download the fonts you want to use. For our example website, ‘BoxofOrganicFresh.com,' we use two fonts: “Roboto” for headings and “Fauna One” for text.[3] These fonts are available on Google Fonts and are free to download.

To get started, click the download button for each font, and you'll receive zip folders containing TrueType font files (.ttf). Extract these files.

STEP 3: OPTIMIZING GOOGLE FONTS

CONVERTING TTF FILES TO WOFF2 AND WOFF FILES

To ensure your fonts load quickly on your website, we recommend converting them into the fastest-loading file types, WOFF2 and WOFF, which are widely supported.

loading google fonts locally starts with generating fonts that are optimized from ttf files into woff2 and woff files
Use ‘Expert' setting in FontSquirrel for advance settings and multiple font downloads.
We'll use the Webfont Generator on FontSquirrel.com for this purpose.[4] It's beginner-friendly and straightforward.

For single loaded fonts in which one weight will be used, we suggest the ‘simple' settings. On the other hand, fonts with multiple variations, like ‘Roboto,' we suggest simplifying your CSS using the ‘expert' setting. The automatic formatting will save you time.

SIMPLE FONT DOWNLOADS (USING ONE .TTF FILE)

  1. Click ‘Upload Fonts' on Font Squirrel.
  2. Select the folder containing your font and its .ttf file (e.g., ‘Fauna One' in this case).
  3. Be patient while it uploads your fonts (there is no progress indicator, so be patient; it might take a minute).
  4. The default setting is ‘optimal,' simplifying your work for this step.
  5. Confirm that you can use uploaded fonts and check the box.
  6. Click ‘Download Your Kit.'

EXPERT SETTINGS (FOR MULTIPLE FONT FILES)

  1. Before uploading .ttf files, remove fonts you won't use. You can always add them later.
  2. Upload your .ttf files into Font Squirrel's webfont generator.
  3. Choose ‘expert' settings.
  4. In the CSS section, check the ‘Style Link' box.
  5. In the ‘Font Name Suffix,' add a label for your design records, like a numerical date.
  6. Leave other settings as they are.
  7. Confirm your rights to use these fonts.
  8. Download your fonts.

STEP 4: ORGANIZING YOUR FONTS

Now that you have webfont .zip folders for ‘Fauna One' and ‘Roboto,' extract them and move all .woff2 and .woff files to your ‘box-fonts' folder. Your fonts are now optimized and ready to enhance your website's performance.

SECTION 2: PREPARING THE STYLESHEET

STEP 1: OPEN YOUR ‘BOX-FONTS.CSS' FILE

Let's continue with preparing the stylesheet for your optimized fonts. Open the ‘box-fonts.css' file you created earlier.

STEP 2: GATHER THE WEBFONT STYLESHEETS

You'll also find ‘stylesheet.css‘ files in the ‘Roboto' and ‘Fauna One' webfonts folders that you extracted. We'll consolidate all the style information into ‘box-fonts.css‘ for easier management.

STEP 3: CUSTOMIZE YOUR STYLESHEET

Think of the Font Squirrel-generated stylesheet as a starting point, not a final CSS file. We'll customize it to meet our specific needs.

STEP 4: SPECIFY FONT LOADING ORDER

Browsers process CSS from the top down, which means the order of font loading is crucial for performance. To optimize this, place the font ‘roboto-bold-20231106.woff2' at the very top of your stylesheet, ensuring it's the first to load in the header. While the gains in load time may be small, they add up—optimization is all about paying attention to the details. The ‘20231106' suffix in the font name is a versioning technique we've implemented in the ‘expert' settings. This allows us to easily identify the version for future updates or when it's necessary to refresh our cache.

STEP 5: CUSTOMIZE FONT-FACE RULES

We'll make similar changes to all the @font-face rules and font files within ‘box-fonts.css.' However, we'll use ‘roboto-bold-20231106' as our primary example.

STEP 6: FINE-TUNE FONT WEIGHTS AND STYLES

Next, let's fine-tune the font weights and styles as needed. Here's a reference list:

Thin: font-weight: 100

Thin Italic: font-weight: 100

Light: font-weight: 300

Light Italic: font-weight: 300

Regular: font-weight: 400

Regular Italic: font-weight: 400

Medium: font-weight: 600

Medium Italic: font-weight: 600

Bold: font-weight: 700

Bold Italic: font-weight: 700

Black: font-weight: 800

Black Italic: font-weight: 800

Update your stylesheet with the appropriate font weights and styles for each font.

Note: When using relative weights to style specific uses for your fonts, like ‘bolder' or ‘lighter,' remember that only four font weights are considered: thin (100), normal (400), bold (700), and heavy (900).[5]

STEP 7: ENHANCE USER EXPERIENCE WITH ‘FONT-DISPLAY: SWAP;'

Lastly, add the property ‘font-display: swap;' to each @font-face rule. ‘font-display: swap;' ensures that the text content is displayed immediately using the system's default font while the web font is downloading. This very important property creates a smoother user experience—especially on slow connections.

By using modern techniques such as font-display: swap;, browsers can display text immediately and fetch images in the background. This ensures that visitors can start reading content right away, which is often their primary reason for visiting your site.

Now, you're ready to use these new assets and create a streamlined user experience. In the following steps, we'll focus on setting up the magic to speed up your site.

Would you like to view the full stylesheet? Click here to view and copy..

SECTION 3: LET'S PUT YOUR OPTIMIZED FONTS INTO ACTION ON YOUR WEBSITE

In this final section, we will guide you through implementing your optimized fonts on your website, bypassing render-blocking, and enhancing your site's loading speed.

STEP 2: PLACING THE ‘BOX-FONTS' FOLDER IN THE TOP-LEVEL DIRECTORY

To ensure that your fonts and stylesheet are accessible, you should place the ‘BOX' folder, which contains ‘box-fonts,' in the top-level directory of your website server. This is indicated in our function instructions by using WordPress' function, ‘homeurl()‘ which for our purposes is equal to boxoforganicfresh.com. This location makes the resources readily available to your website. This is done using an FTP service like Filezilla.

Here's the recommended structure. This is recapping the information we gave in Section 1 | Step 1:

  • Your Website's Top-Level Directoryhomeurl()‘. Using FTP transfer this file (all the rest will follow)
  • 📁 BOX(contains ‘box-fonts' and ‘box-fonts.css')
    • 📁 box-fonts (contains optimized .woof2 and .woof font files:
      • the fonts as .woff2 and .woff font types.
    • 📃 box-fonts.css (the font style sheet is inside BOX folder)

By following this structure, your fonts and stylesheet are organized and easily accessible.

STEP 1: ADD CODE TO YOUR ‘FUNCTIONS.PHP' FILE

To get started, you'll add specific code to your WordPress child theme's functions.php file. Locate it in your child's theme. It will be in the files directly under your child theme's folder.

We recommend that you first back up this file, and then add this function directly after the opening tag <?php that initiates your .php file. Note: This is a different approach, because most developers will ask you to put additional code further down your functions.php file after CSS and JS scripts have been enqueued. We want to make this function to load before any other file is loaded in the queue.


/**
* Attention WordPress Enthusiasts!
* Optimize your website's load time by serving google fonts from local files.
* This php code is placed at the very top of your child theme functions.php file
* Directly after the <?php open tag and before your function sheet enqueues other 
* .js and .css files
* BACK UP YOUR ORIGINAL FILES FIRST!!!!
* 
* A special shoutout to the team at Box of Organic Fresh for their ingenuity in authoring 
* and meticulously testing this function. 
* Their contribution is invaluable to the WordPress community.
* 
* Support the site by visiting us: https://boxoforganicfresh.com
*
* **Let's make the web more accessible, one image at a time!**/


// author: boxoforganicfresh.com

function custom_enqueue_google_fonts_and_stylesheet() {
    // Define the paths to the font files and CSS on your server. Change 'BOX' to your custom folder after you have made this work for you.
    
    $font_url = esc_url(home_url('/BOX/box-fonts/roboto-bold-20231106.woff2'));
    // Change the 'box-fonts.css' if you rename this file.
    
    $style_url = esc_url(home_url('/BOX/box-fonts.css'));
    // This custom code will be injected directly under the <head> tag where it loads before other .css files.
    
    echo "<link rel='preload' href='$font_url' as='font' type='font/woff2' crossorigin>\n";
    echo "<link rel='stylesheet' href='$style_url' type='text/css' media='all'>\n";
    echo "<link rel='preconnect' href='" . esc_url(home_url('/')) . "' crossorigin>\n";
}

add_action('wp_head', 'custom_enqueue_google_fonts_and_stylesheet', 1);

We created this code to be injected at the top in your header for two reasons:

  1. You won't have to directly edit your header.php template (which adds a whole other level of more instructions by us for new designers or WordPress developers), and:
  2. And, you can better control the font loading position at the top. This will act as a bonus for the order in which your site loads from the child theme.

To illustrate the load position and time, here are two images of GTMetrix in evaluating the load time and savings.

Before New Loading Google Fonts Locally Function
Before loading google fonts locally, the images slowed down the page by blocking the rendering of fonts because they didn't start to load, therefore slowing down the page. This is common with loading Google fonts through their CDN

This code function custom_enqueue_google_fonts_and_stylesheet() accomplishes the following:

  • It defines the paths to the font files (where your ‘roboto-bold-20231106.woff2' is called first) and the CSS file (‘box-fonts.css') on your server.
  • It adds preloading instructions for your fonts (initiated by ‘roboto-bold-20231106.woff2'), which helps browsers anticipate the resources they'll need.
  • It loads your custom stylesheet to apply all of the fonts you'll use to load google fonts locally.
  • And, because it is injected in the head, the fonts will be accessible throughout the journey your users take for your website and this will not put an additional load on your server, because they will be cached in memory.
After LOADING GOOGLE FONTS LOCALLY
After New Loading Google Fonts Locally the fonts begin loading before the images. This decreases the total load time

Lastly, among other benefits, by you putting this function before you enqueue CSS and JS files (or,at the top of your functions.php), as we suggested, fonts will load before images. This approach aligns with the browser's priority to load essential resources like fonts and stylesheets first. Fonts are crucial for legibility and the overall look of your site, so they should be available early on.

Section 4: Ensuring Performance

Caching .WOFF2 in .htaccess File


## CACHING .WOFF2 IN .HTACCESS FILE
<IfModule mod_expires.c>
  ExpiresActive On
  AddType font/woff2 .woff2 
  ExpiresByType font/woff2 "access plus 1 year"
</IfModule>
## END CACHING .WOFF2

To cache .woff2 font files in your .htaccess file, you'll need to ensure you have access to it, which is typically found at the top level of your website and can be accessed through FTP. The .htaccess file is a powerful tool for improving speed and performance, but be cautious—incorrect edits can crash your site. Always back up your file before making changes, test your site immediately after editing, and if you're unsure, consider consulting an expert for this step.

If you're using a caching plugin, verify that it's properly caching your .woff2 and .woff font files. The code snippet provided above will add caching for .woff2 fonts for one year, which is the recommended practice for modern web performance.

.woff2 fonts are now widely supported across all modern browsers. However, they may not be included in older optimization recommendations. For most sites, loading .woff2 and .woff fonts is sufficient as they offer the best balance of performance and compatibility, except for very old browsers. If your design cannot accommodate a default browser font and requires a specific custom font, then including fallbacks like .ttf, .svg, .otf and .eot files is advisable. While this guide doesn't cover how to add these formats, there are many resources available online that provide detailed instructions.

Empowering Your Troubleshooting

Proactive Solutions for Font Loading

Should you encounter issues with font loading, it's likely a sign to double-check your folder structures and path configurations. We suggest starting with our provided file setup and structure. Only after confirming they work should you consider renaming files, switching fonts, or altering font paths.

Optimizing for Reliability

In instances where your inspection reveals missing fonts, revisit your path setups. If everything appears accurate and all files and fonts appear to be placed in their correct paths, try uploading the .woff2 and .woff files in a compressed format and then decompress them within your website's file system, ensuring you have server file access.


Customization and Caution: A Framework for Your Website's Unique Needs

These guidelines are designed to be a starting point, adaptable to your unique file naming conventions and font preferences. It's essential to create backups and rigorously test all code and site functionality before finalizing any changes.

It's not uncommon for web developers to face surprises—finishing a day's work believing everything is perfect, only to wake up to unexpected issues. Mistakes are part of the learning process.

This also happens when loading Google Fonts locally. The paths, file names and the correct CSS and PHP matter. Human error is 99% the problem for test code that works everywhere but your own website. 1% is usually the error of another person's error. •ᴗ•

We offer these instructions based on our experience with numerous projects. However, they may not universally apply, especially if your theme requires specific adjustments, or you need to modify additional .js or .css files.

While we strive to provide helpful advice, we cannot offer personalized troubleshooting or guarantee that our recommendations will work in every situation. Always remember to back up your work and conduct tests on development environments before implementing any new changes you find online.

We wish you the best in your web development journey and hope our insights contribute to a superior online experience for your audience!


Suggested Reading and Article Research Credit

  1. WordPress explains ‘Child-Themes' in easy-to-understand language that most beginner web developers and designers easily understand↩︎
  2. To read and gain an understanding of GDPR (“General Data Protection Regulation”)↩︎
  3. Roboto and Fauna One links if you want to follow along with these instructions.↩︎
  4. Webfont Generator on FontSquirrel.com↩︎
  5. To learn more about how to optimize your font styles, Mozilla has created this information.↩︎

🌱💪Our Recommended Products & Services

Tools and Resources for Developers and Web Designers

Bose QuietComfort Wireless Noise Cancelling Headphones: Boost your productivity and focus with these premium noise-cancelling headphones. Ideal for developers and web designers who need a quiet environment to concentrate, these headphones offer up to 24 hours of battery life and seamless Bluetooth connectivity.

The Startup CTO's Handbook: Essential Skills and Best Practices for High Performing Engineering Teams by Zach Goldberg: Elevate your leadership and technical skills with this essential guide. Perfect for current and aspiring CTOs, this handbook provides valuable insights into building and managing high-performing engineering teams, making it a must-read for tech leaders.

Wireframe Sketchbook for UX/UI Designers & Developers by Purple Lemon Press: Streamline your design process with this practical sketchbook. Featuring dot grid and mobile phone templates, it's ideal for creating user interface designs for apps and websites, helping you visualize and prototype your ideas effectively.

0 comments on “Loading Google Fonts Locally: Start From The Top for SpeedAdd yours →

Leave a Reply

Your email address will not be published. Required fields are marked *