Optimizing SEO with Loadable Components in Gatsby
The Challenge of Asynchronous Loading
When building a website with dynamic data, we often face the dilemma of choosing between asynchronous loading and SEO optimization. Asynchronous loading can improve user experience, but it can also hinder search engine crawlers from indexing our content.
The Problem Statement
We have a Gatsby site that uses a content management system to render information and modules. The site is a blog that displays posts, and we’d like to add custom blocks to render non-blog post content. However, these custom blocks require different React components depending on their design. To implement this, we created a file that uses the custom block’s name to render its corresponding component.
The Limitation of Current Implementation
Our current implementation loads all custom blocks and their components simultaneously, which can lead to performance issues. Imagine having numerous custom blocks – it would be inefficient to load them all at once. This is where loadable components come in.
Introducing Loadable Components
Loadable components allow us to load components asynchronously, optimizing performance. By adding loadable components to our code, we can ensure that custom blocks are loaded only when needed.
import loadable from '@loadable/component';
const CustomBlock = loadable(() => import('./CustomBlock'));
Configuring Loadable Components for SEO
To address the issue of custom block content not being pre-rendered into the static HTML, we need to make some configurations to our loadable component setup.
- Install the necessary dependencies:
npm install --save @loadable/babel-plugin
- Add a custom Babel plugin:
//.babelrc
{
"plugins": ["@loadable/babel-plugin"]
}
- Modify our webpack plugin:
// gatsby-node.js
exports.onCreateWebpackConfig = ({ stage, actions }) => {
if (stage === 'build-html') {
actions.setWebpackConfig({
plugins: [
new LoadablePlugin({
//...options
}),
],
});
}
};
Pre-rendering Custom Block Elements
We can use the fallback prop of loadable components to pre-render custom block elements in static HTML.
import loadable from '@loadable/component';
const CustomBlock = loadable(() => import('./CustomBlock'), {
fallback: (
),
});
const getRenderedContent = () => {
// Return the rendered custom block content
};
The Result
With these configurations in place, we can build and run our site in production. The dates are now visible in the page source, indicating that custom block elements are being pre-rendered, making it possible for crawlers to successfully crawl the page.
Try it Out
To simulate this setup, you can visit our GitHub repository, which contains the codebase for the Gatsby project and an exported Contentful space. Follow the instructions to set up the project and connect it to your Contentful space.