These days, we can add almost all external Javascript into our project as npm/yarn packages. However, there may be times when the external resource is not available as an npm/yarn package, for example, when you want to add a Zoho Campaign Newsletter Form. Your only option is to include it directly as a script file. But with the way Gatsby is structured, that might be a little difficult.
Nevertheless, there are a couple of workarounds to load external script files into your Gatsby project, and we’ll go through them.
1. Using Gatsby’s html.js file
This method is suitable when you want to execute a script globally on every page. The html.js is not visible in the source tree by default, so you need to extract it using: cp .cache/default-html.js src/html.js
Then proceed to add your script file. However, according to Gatsby, this method should only be a workaround solution for when the use of the appropriate APIs is not available in gatsby-ssr.js
. Also, it is not supported in Gatsby themes, so you may need to consider other methods.
2. Using Gatsby SSR onRenderBody API
Gatsby provides server-side rendering (SSR) APIs that allow you to change the content of static HTML files as they are being Server-Side Rendered (SSR) by Gatsby and Node.js.
One of such APIs is the onRenderBody, which is called after every page that the Gatsby server renders when generating HTML, allowing you to specify which head and body components should be rendered in your html.js.
First, create a file create a file called gatsby-ssr.js
in the root of your site
Let’s say we want to add some script just before the body closing tag, we’ll use the setPostBodyComponents
method:
And that’s it.
Note that all scripts must have a unique key attribute. See the official doc here.
3. Using Gatsby-plugin-load-script
Gatsby-plugin-load-script helps you add external libraries to your Gatsby website
First, install via npm or yarn: npm install gatsby-plugin-load-script
Then in your gatsby-config.js file, add:
{
resolve: 'gatsby-plugin-load-script',
options: {
src: 'https://test-script.js', // Change to the script filename
},
},
Blog Credits: Linda Ikechukwu
Comments are closed.