Road with zooming lights and the title of the article overlayed.

19 Steps to Build a Lightning-Fast Gatsby Website

The gatsby frontend framework already creates fast websites because static websites will always be faster than dynamic ones, provided all other technical aspects remain the same. The speed of a website’s load-time has been officially confirmed by Google as a ranking factor, and also corroborated in the largest test of page speeds ever performed. There are several advanced procedures and steps you can undertake to ensure your gatsby website runs at lightning speed. In this article, we look at them in depth. 

But first, what constitutes page speed?

Understanding website speed

Website speed is not a unit subject. It breaks down into several sub-topics. The key elements to understand about page-speed are:

  • Server response time: If you’re on a server with little memory and processing power, and you’re sharing your hosting space with 1,000 other websites, no amount of front-end tweaks is going to improve your page-load time very much. Before anything else, you need to ensure you’re on a decent server that responds quickly to HTTP requests or that you’re using the correct CDN/caching setup to reduce server-load per request.
  • Time-to-first-byte (TTFB): This is the time taken before the first byte of data is received by the requesting client. According to SEO expert Neil Patel, it has an incredible impact on search engine rankings. Static websites (such as those produced by gatsby) generally have a better TTFB because the content is ready to be served. But dynamic websites have to generate the content newly on the server for every single request.
  • First-contentful paint (FCP): MDN defines this as “when the browser first rendered any text, image (including background images), non-white canvas or SVG. ” It is an essential aspect to pay attention to for an improved user experience.

How important is speed in a website?

The following data chart should give you an inkling of just how vital page load speed is for website conversion rates and keeping your visitors.

Consumers who admit page speed influences their desire to buy (source: unbounce)72%
Percentage of people who are less likely to buy when a website loads slowly (unbounce)45.4%
Number of people who would give up videos for faster load times (unbounce)52.8%
Percentage of marketers with below-par load speeds (unbounce)85%
Percentage of people who won’t wait longer than 6 seconds for a page to load on their phones (unbounce)59.2%
Drop in conversion rate per additional second of page load time (HubSpot)4.42%
Increase in probability of a mobile visitor bouncing as load time goes from 1 - 10 seconds (Google, 2017)123%
Increase in probability of page bounce as load time goes from 1 - 3 seconds (Google, 2017)32%
Percent of pages that could save over 250KB by simply compressing images and text (Google, 2018)25%

Here’s a graphical representation of the data chart above:

A bar chart titled "Page Speed Matters" which represents the data in the table above.

How to test your gatsby website speed

The PageSpeed Insights and Lighthouse tools are both excellent choices for testing your website speed. I prefer Lighthouse because it offers more actionable and insightful data on how to resolve the underlying causes of a slow-performing website, whereas PageSpeed Insights tends to focus more on the metrics only.

Steps to build a lightning-fast gatsby website

Okay! Here are my 19 top tips for building a lightning-fast gatsby website.

#1. Code splitting

Code splitting refers to the practice of splitting chunks of code into separate files and only loading what is needed per request. This is commonly done for CSS and JS files so that only the CSS/JS needed for that specific page is loaded, reducing the overall load that must be returned by the server. This is particularly important in speeding up websites when they’re being called from a mobile data connection as opposed to WiFi.

One caveat of this is that, if it is done poorly, it might result in too many requests for different files when fewer requests would do. Another caveat is the possibility that styles might be loaded in the incorrect sequence resulting in overriding previously defined styles.

Still, if done properly, code splitting can work wonders for speeding up your gatsby website’s page-load time. I recommend using gatsby-plugin-split-css for CSS code splitting.

Gatsby automatically splits javascript by the page but if you also want to split it by individual components you can use the loadable-components library to lazy-load the components. Component splitting is optional but can help if you have heavy javascript components like a slider below the fold.

#2. Font preloading

Font preloading is the act of telling a browser to fetch fonts from a server even if it doesn’t know what those fonts will be used for. It is a key way to improve the first contentful paint (FCP) metric.

Along with font-preloading of above-the-fold fonts, using font-display: swap in your CSS will make sure FCP is unaffected by fonts. Preloading fonts just gives the user a better experience by showing the fonts we want faster. But you should always use font-display: swap or font-display: optional, or font-display: fallback when loading custom fonts because merely preloading can still give us a bad FCP if the font is large. Using font-display: swap or similar will mitigate this completely.

To preload fonts to increase your gatsby website speed, you can use the gatsby preload fonts plugin or implement your own solution.

#3. Load fewer font weights and use fewer subsets

A “script subset” of a font is a smaller font file that contains only the characters you need. Also, some fonts come with many different weights. Designers rarely use these different weights so loading all of them is unnecessary and will slow down your page’s load.

How to load only a font subset or specific font weights depends on the font you’re using and where you’re loading it from. Google web fonts lets you specify the specific weights you want to load, for example. Ideally, however, you should host fonts yourself, and preferably on a CDN as it cuts down on DNS time.

#4. Use good old system fonts

Long live Arial font! By loading “safe web fonts,” you greatly simplify (and speed up) your gatsby website because the font will be sitting on the user’s device already. Of course, universal system fonts are greatly limited and this might detract from the website’s aesthetic appearance.

#5. Use WOFF2 fonts

WOFF2 fonts are a new font format that can reduce a font file’s size by 30%. You should always use them in your gatsby project to make your gatsby website lightning fast.

#6. Embed fonts using data:font

Embedding fonts as a base64 string in your HTML file can speed up your gatsby website by removing one more HTTP request from your page. The only caveat is that it might slow down the initial document download time.

#7. Use preloaders (loading screens)

If your gatsby website is truly resource-intensive, one option is to display a preloader/loading screen to entertain the visitor while the rest of the content is fetched or painted. A preloader can be anything—a simple HTML element, an image, plain text that the user can start reading, etc.

This site contains an example of how to create one type of preloader for your gatsby website.

#8. Export only the font icons you need

Font icons such as Font Awesome are popular for adding intuitive icons to a website. Their popularity and ubiquity means they are easily recognizable by users and go a long way to decluttering an interface and giving it extra polish.

But with over 7,800 icons, loading the entirety of a Font Awesome resource for a website that would only use a handful of them is wasteful. Font Awesome comes with a subsetter app that allows you to pick just the icons you are going to use in your website, making it far leaner.

Another option is to use a tool like icomoon.io to pick icon subsets to make your gatsby website faster. But if you do, you should know that icomoon.io only exports fonts as WOFF 1.0 for non-premium members. So, you should convert these fonts to WOFF 2.0.

#9. DNS-prefetch and preconnect

DNS-prefetching is a directive added to a resource to tell the browser to perform a DNS lookup of the resource. Preconnecting means the browser should do a DNS lookup, complete the TCP handshape, and finish the TLS negotiation. This makes loading that resource much faster when it is time to actually use it.

Internet Explorer does not currently support preconnect, so you would have to use dns-prefetch in those cases.

You can add preconnect functionality to a gatsby website by using the preconnect gatsby plugin.

#10. Extract critical CSS

Critical CSS is the bare minimum CSS required for above-the-fold content. Having this CSS being the only styling extracted into the document head can improve the FCP (First Contentful Paint) for the end user.

As far as I know, there is no easy way to do this in gatsby, although users of the Linaria CSS (a CSS in JS solution) plugin do receive critical CSS extraction when they opt in to it.

For more info on this topic, you can check out this discussion.

#11. Use the PurgeCSS plugin

The gatsby PurgeCSS plugin removes unnecessary CSS from files and modules within your gatsby project. According to the plugin’s page, this is not an “install and forget” plugin and it requires regular monitoring to ensure that styles don’t break.

Still, the removal of CSS bloat can go a long way to speeding up your gatsby website.

I recommend using PurgeCSS to purge CSS from large libraries such as bootstrap. But you should always manually purge the CSS you write yourself.

#12. Optimize images

Optimizing images can have one of the most marked effects on a site’s speed. Images in the wrong format or wrong resolution can grind a site’s load-time down to a halt, bringing back nightmares of the early days of the web when huge BMP images plagued our browsers.

JPG and PNG have been far better contenders for speed, but now a new format—webp, developed by Google—creates even smaller images. Converting your images to this faster format could give you the fastest immediate gains on your gatsby website’s speed.

The gatsby image plugin will also allow you to optimize images in various ways, with many different settings options available to improve how your site delivers images.

#13. Use SVG or custom CSS for logos

If you’re really trying to cut down on bandwidth, you can use SVGs or custom CSS to recreate your logo instead of serving an image file.

#14. Lazy load images below the fold

Lazy loading is an excellent way to speed up a gatsby website, and it refers to the practice of serving a low-quality placeholder for an image until the user scrolls down to the section of the page where he or she can view the image.

The great news is that this feature works straight out of the box using the gatsby image plugin. All you need to do is specify which placeholder image to use and the plugin takes care of the rest.

You should, however, set the loading property to “eager” for above-the-fold images otherwise they will also be lazy-loaded, which is not necessarily the greatest experience for users.

#15. Decrease bundle sizes and find smaller libraries

According to Lighthouse, a resource’s blocking time should be less than 50ms. There’s a library/bundle for virtually anything out there these days but randomly choosing libraries without paying close attention to their size and their blocking time can end up bloating your gatsby site and slowing it down unnecessarily.

For example, using a 100KB alert box library when you only need one type of alert box is inefficient. (I’m looking at you, SweetAlert2!)

Analyzing each and every bundle might be tedious, but it’s important if you want to keep your gatsby website fast.

#16. Use a CDN

Using a CDN to deliver resources can have an enormous impact on a gatsby website’s overall speed. CDNs are optimized to serve resources most efficiently according to where a request is coming from. They also have powerful caching capabilities that further speed up the delivery of static resources.

I personally recommend Netlify as a CDN.

#17. Use defer and/or async for render-blocking javascript files

For non-critical render-blocking javascript, using the defer and async directives means your site can load up completely without waiting for the javascript resources to be loaded first.

Specifying defer means that a javascript file will only start executing as soon as the document parsing has been completed. When specifying defer, javascript files will be executed in the sequence that they are loaded.

When specifying async, a javascript file will be loaded asynchronously, and will execute as soon as the load is finished. There is no guarantee as to what sequence the files will be executed in when using async.

#18. Load unimportant page elements only after scrolling

For any elements that are not vital for search engine indexing, you could code your gatsby site to only load those elements after the user has scrolled to that section.

#19. Swap React for Preact

Preact offers a subset of the full React.js ecosystem and is more than enough for most uses within the gatsby framework. The preact pack size is also 30KB smaller than React. To swap React.js for Preact, use the gatsby preact plugin.

Summary

There you go. These 19 steps will make any gatsby website lightning-fast!

Much more can still be done to speed up a gatsby site, but the above will get you most of the way there. I recommend looking through the Lighthouse report for your particular site and working through further recommendations. Shaving off milliseconds here and there from many different elements can have a profound impact on the overall site’s performance.

 

LOADING COMMENTS