TABLE OF CONTENTS

Gatsby Website Performance: 2022 Technical Guide

GET YOUR GATSBY WEBSITE Performance WHERE IT SHOULD BE

Improving your Gatsby website performance is more important than you think. Sure, Gatsby websites and apps are fast, and since static websites and apps outperform dynamic ones by default it shouldn’t be much of a surprise.

However, with a little optimization, both Gatsby websites and apps can get even faster. Much faster.

In this article, you’re going to learn how to get your Gatsby website performance faster & smoother.

If you want to cut right to the chase and start coding, feel free to skip right to the Technical Part.

What’s So Special About A Gatsby Site?

Gatsby, just like many other static site generators, allows you to build and deploy fast static websites great for improved SEO and overall conversion.

Gatsby is a React-based, free open-source front-end framework that works as headless CMS. When using gatsby build, a Gatsby website creates static HTML at build time using the same APIs, rather than rendering 100% server-side.

What’s more, Gatsby company offers a headless Jamstack integration, which makes the websites faster, better, and stronger.

Gatsby Sites & Jamstack Integration

Gatsby Jamstack integration gives you a massive advantage over pretty much any other management system when it comes to speed, performance, and SEO positioning.

It’s a great fit for the vast majority of different headless CMS and eCommerce platforms.

Check out this article to learn more about Jamstack.

Improving Gatsby Site Performance – Is It Worth It?

And the answer is… it depends.

Since static websites are generally more performant than their dynamic counterparts you might think that you’re good with what you have. And yes, a Gatsby website will generally be faster than a classic CMS like WordPress, even if it’s a completely new gatsby site that is yet to be optimized. Keep in mind, however, that a well-optimized WordPress site can do great as well.

Either way, when running a Gatsby website you’re not competing with your regular WordPress users alone. You’re also competing with other, blazing-fast static sites. If you want to beat them, you need to go a step further.

It’s All About SEO And Google Rank

It’s no secret why everyone is so obsessed with website speed and performance. Google and other search engines rank our websites according to a number of criteria, and load time is a big one.

Let’s take a look at a couple of key SEO features that Gatsby sites offer.

Gatsby Is Greater Accessibility

There’s a good reason why Gatsby had been previously named the most accessible web framework. Gatsby is a top-tier static site generator that offers the greatest accessibility to everyone, including those with temporary or permanent disabilities.

Gatsby Is Better Page Metadata

Metadata makes it easier for Google’s robots and other search engines to find your website. These robots scan your website looking for clues as to what your website is all about. Gatsby makes this process easier, making their work smoother, and the quicker they can grasp the core of your website, the quicker they know how to rank it.

Gatsby Is Faster Page Load

Page load is one of the absolutely most important factors when it comes to ranking on Google. Each extra second your website takes to load causes a 7% conversion loss. To put it simply, the faster you are, the better you convert. It’s really straightforward.

Gatsby Is Structured Data

Apart from the meta data, the structured data helps Google understand the content of your Gatsby website. If the data is structured appropriately, Google can read it quicker and make more detailed deductions. That way, search results are more relevant to the user’s search intent, and if that intent matches the content of the website, the website is ranked higher.

Gatsby Is Improved User Experience

Gatsby allows for great customization. Since you have more control over how your Gatsby website looks and feel, you’re able to deliver a greater user experience. Also, Gatsby is generally error-free and really fast – who wouldn’t like this sort of combination?

Gatsby Is Top Security

No direct connection between your Gatsby website and database, dependencies, user data, and other sensitive information, guarantees no bad guys can mess with your GatsbyJS sites.

Quick poll

Are you a Gatsby Developer?

8 votes

The Technical Part

In this part, you’re going to learn about practical ways of improving the performance of your Gatsby website. Here, you’re going to find code snippets along with explanations, examples, recommended plugins, and more. Ready to code?

What’s Website Performance And How to Measure It

Website performance is measured and delivered in a form of a report that informs you about the score of your website (on mobile and desktop devices) and suggests how to improve it. The result is based on four measurement properties: First Contentful Paint (FCP), First Input Delay (FID), Largest Contentful Paint (LCP), and Cumulative Layout Shift (CLS). Three of those metrics – FID, LCP, and CLS – are The Core Web Vitals, which means their performance is critical for the overall page speed score.

The score can vary because performance measurements occur in variability. In general, the performance of your website is determined by the local network, internet traffic, user hardware, or resource contention.

What Are The Web Vitals

Let’s go over what Web Vitals are and how they impact the performance of your Gatsby site. Full descriptions of these parameters can be found in this blog post.

Core Web Vitals are a set of criteria according to which all web pages are rated. They include The Largest Contentful Paint (LCP), The First Input Delay (FID), and the Cumulative Layout Shift (CLS).

  • Largest Contentful Paint (LCP) – this indicator measures the loading efficiency of a website by measuring the largest element requiring the most time to process. An Optimal LCP result is up to 2.5 seconds on the first page load. Anything over that means that your Gatsby site needs to get some work done.
  • First Input Delay (FID) – Used to measure the time your Gatsby site takes to respond to the first interaction. If it’s more than 100 milliseconds, then, again, you need to get started on working to improve your Gatsby site.
  • Cumulative Layout Shift (CLS) – CLS measures how visually stable your Gatsby site or web app is by calculating the sum of all individual page layout shifts that occur during the page load. Anything above 0.1 is bad news.

Example tools For measuring page performance

  • PageSpeed Insights – prepares performance report/analysis of the website.
  • Web-vitals – lightweight JavaScript library for measuring The Core Web Vitals. It is a wrapper that measures each metric for the project during production builds.
  • ​​Netlify Plugin Lighthouse – a Netlify plugin that generates a lighthouse report on every deployment.
  • Lighthouse CI – generates the lighthouse report as the link on each commit.

want to take your website to the next level?

Monitor performance with every change you make

It is easier to control page performance metrics with every single change you make than at the end of the project where there are many components, and sections and it is hard to find the source causing speed problems.

Create pull requests with every single feature, and if your deploy service allows it, check the performance score on each deploy preview for the branch before merging the changes.

Media & Image Optimization

Images, videos, and other media are often the largest files on the website. It’s always a good idea to compress these files before uploading them onto your website. Any delay when trying to download these files (e.g. lazy-loading) can have a significant impact on the site’s overall performance. It’s also a good practice to use WebP image format as it provides lossless compression. WebP format images are usually much lighter than their equivalents in other formats, such as png.

Gatsby Image Optimization

While uploading images to the project it is important to take care of their optimization as it can reduce the size of the file a few times. Some browsers like Firefox, Chrome, and Edge support loading=”lazy” for img tag. This means the file will be fetched once the user scrolls to the image.

Gatsby has its own way of handling images and their optimization through the gatsby-plugin-image. The plugin minimizes the size of the image and provides the placeholder for the image while it is being fetched. Also, gatsbyimage will prepare different images for different breakpoints – mobile devices will load smaller images than desktop ones.

Here is a previous blog post with a full description of adjusting gatsby-images for better performance.

Use gatsby-link for internal redirects. Because of the fact that Gatsby is serverless and preloads linked pages, the usage of gatsby-link optimizes navigating between (internal) sites.

Font Optimization

Fonts block page load and optimizing them can have a significant impact on your website’s score. 

First, when declaring the font faces, remember about font-display property. Setting it to swap will trigger the browser to set the font to default at the beginning of page load. When the desired font is ready, it swaps to it.

Second, it’s better to self-host the fonts than to rely on external sources. It reduces the time to fetch the fonts. Also, it is good to use any tool for optimizing font files.

Styles Optimization

Write styles for the app in a clever way as every additional style will make the bundle size bigger. 

  • Avoid repeating CSS code. You should always strive to write reusable styles for content that is replicated on the website. You’re far better off writing one component with proper styles than writing a few with similar, repetitive styling.
  • Make sure to remove code parts that are not being used. External libraries like Tailwind offer ready-to-go styles for elements but also consist of a lot of CSS code that in some parts is unused.
  • Avoid using content delivery network (CDN) as it increases HTTP connections.
  • Write simple selectors – the less nested CSS code, the better – reducing complications of the code will reduce file size.
  • If there is a need to add the decor in CSS, you should try to prepare it with styling rather than by using background-image. However, if background-image is necessary, SVG can be helpful in this case as these elements can be written inline in CSS code and do not require additional requests to the image file. 
 background-image: url('data:image/svg+xml;utf8,<svg>...</svg>');

First visible element(s) on the page

A quick and easy way of improving your website speed and score is to make sure the elements which are first in order on the website are always visible (when hitting the page), static and do not change during the period of initial page load. This behavior positively affects the measure of the Cumulative Layout Shift – CLS.

During this short time of initial page load it is good to:

  • keep the height and width of the elements so they won’t jump on the screen,
  • avoid loading additional elements (like popups).

Code splitting

Some components like maps or videos require external libraries/resources. These resources are loaded on the initial page load, which greatly affects the project main thread. In most cases it’s not beneficial in any way as the components using external resources are not placed on the top of the website, but below the initial, visible window area. In general, applications built with CRA, Gatsby, and Next.JS use webpack for bundling. Bundler imports all the files at the same time and merges time into one bundle.

Code splitting helps to reduce the size of the main bundle and keeps some parts of the code in other packages which are dynamically loaded to the application code. It means that less code will be loaded on the application start and only “at the moment” needed code will be fetched.

Code split example (source – https://vueschool.io/articles/vuejs-tutorials/lazy-loading-and-code-splitting-in-vue-js/)

React.lazy() 

To defer the loading of the component and related resources in React, you can use dynamic import React.lazy(). The React.lazy() function will automatically import the component during the first rendering of the component. It will expect a module returned with the default export. The component will be rendered inside React.Suspensewhich provides a fallback that will be shown while waiting for the component to load. Suspense allows you to withhold render of the component until it will have loaded. Multiple components can be wrapped in Suspense. Additionally, the time of loading the component can depend on the state. For example, it can be loaded when it is visible in the viewport.

import React, { Suspense, lazy } from 'react';
const Component = lazy(() => import('./component));
...
{isVisible && (
  <Suspense fallback={<Loader />}>
    <Component />
  </Suspense>
}

Loadable Components

A code-splitting library can be helpful when React.lazy() is not enough. Loadable components also work with Suspense, but it is not necessary to use it together like with React.lazy(). The solution allows us to use dynamic values that can be applied in a dynamic import.

import loadable from `@loadable/component`
 
const Component = loadable(props => import(`./${props}`));

Third-party scripts

Loading all of the third-party scripts can hinder page load and have a destructive impact on performance. It affects the time to interactive metric, which has a noticeable impact on mobile devices and is an important one for Google rankings.

Even scripts loaded asynchronously have an influence on that score. 

When working on desktop devices with a good internet connection the time to interact is nothing to be concerned about, but everything changes for mobile devices, where the performance can get really bad.

Partytown library is an experimental package that helps run third-party scripts separately from the main thread using web workers. To make it work you need to install the package @builder.io/partytown. Next, each script that shall be run from a web worker, needs to have a defined type as text/partytown. That kind of type tells the browser not to proceed with the script. Once the document will be ready and the Partytown will be initialized, the library will trigger all the scripts with type equal to text/partytown.

<script type="text/partytown">{code}</script>

Examples of the implementation in the Gatsby can be found in the docs.

Note that this solution is still in development and not all of the third-party scripts will cooperate with it. Library provides a list of tools that work out of the box. A few examples are Google Tag Manager, Hubspot Tracking, and Facebook Pixel.

Summary

Controlling the performance of websites during development is an important part of the process. A user’s interaction with your site influences whether they are going to keep using the app. Even an application with well-written code will not get much traffic if the load time is poor. 

5 seconds may seem like a relatively short snippet of time, but in the online world, very few users are ready to wait that long for a website or app to load. They want to be able to use them instantly.

All in all, besides good practices while writing your code do not forget and underestimate the performance of the website and its pagespeed score as it has a huge impact on your digital product and how well it performs.

Article link copied

Close button