I am using Gatsby and need to head a script in the header BEFORE other plugin.
If I add it via gatsby-ssr.js
exports.onRenderBody = ({ setHeadComponents }) => setHeadComponents([#MY-SCRIPT#]);
it's being added last.
How can I add it BEFORE other plugins?
Since the release of the Script
Gatsby component (powered by Partytown) it's much easier adding third-party scripts. Just:
import React from "react"
import { Script } from "gatsby"
function YourPage() {
return <Script src="https://my-example-script" />
}
export default YourPage
Why you use gatsby-ssr.js
file if you can use <Helmet>
tag, maybe it fits you. You just need to use it like this in any component:
import React from "react"
import Helmet from "react-helmet"
import Layout from "../components/layout"
import SEO from "../components/seo"
const IndexPage= () => (
<Layout>
<SEO title="Index page" />
<Helmet>
<script src="https://whatever.com" type="text/javascript"/>
<script src="https://whatever2.com" type="text/javascript"/>
</Helmet>
</Layout>
)
export default IndexPage
The snippet above will load your scripts inside <head>
tag on the same order you've placed it.
If you need some kind of ordering and async approach, you can use gatsby-ssr
, across onRenderBody
and onPreRenderHTML
.