7

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

1
  • It will be better if you put more details in your question. Commented Feb 4, 2020 at 7:00

3 Answers 3

7

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>,
      ]),
    }
Sign up to request clarification or add additional context in comments.

2 Comments

But where those files have to be placed? It is not clear how it can find those files locally. PS: anyway it is not working for me, I get a 404 when I try to load the assets
Unless I need to copy myself those files myself in the public directory.
3

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/.

1 Comment

Hi @DeepKakkar, I want to add tweenmax.js in my gatsby project, how should i add it ?
1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.