Reputation: 85
I want to know how to add external javascript file to gatsby, where should i put these tag in which file ? And also how to import the file properly to the DOM.
Thanks
Upvotes: 7
Views: 6024
Reputation: 747
You can add this part of code in you gatsby-ssr.js, this add code in your balise .
export const onRenderBody = ({ setHeadComponents }) => {
setHeadComponents([
<link
rel="stylesheet"
href="/style.css"
/>
])
}
You Have the same for the body
export const onRenderBody = ({ setHeadComponents, setPostBodyComponents }) => {
setHeadComponents([
<link
rel="stylesheet"
href="/style.css"
/>
]),
setPostBodyComponents([
<script></script>,
]),
}
Upvotes: 7
Reputation: 101
You can always use html.js to add HTML tags, but better use npm packages to add the libs. Here are the docs on how to do it with html.js: https://www.gatsbyjs.org/docs/custom-html/
Upvotes: 1
Reputation: 6297
You can choose any one way as follows:
a. Use Plugin You can use gatsby-plugins to add external scripts such as Google Tracking Code, Google Tag Manager, Hubspot code, etc.
In order to use gatsby plugin on your website, search for the plugin in gatsby org website https://www.gatsbyjs.org/plugins/ and follow the steps to add it in your site.
b. Use gatsby-ssr.js Suppose you want to add scripts or a list of scripts but there is no plugin in gatsbyjs. Still, you can add external scripts.
For it, you need to use gatsby SSR API https://www.gatsbyjs.org/docs/ssr-apis/.
Upvotes: 3