I have this page created on Gatsby and I'm including this Script from Sharpspring in the Helmet component and it loads sometimes but not all the time. Any ideas why this happens?
import React from "react"
import ReactDom from "react-dom"
import LayoutTemplate from "../templates/LayoutTemplate/LayoutTemplate"
import { Helmet } from "react-helmet"
const Preferences = () => {
return (
<LayoutTemplate>
<Helmet>
<script async type="text/javascript" src="https://koi-3QNLLDDY3O.marketingautomation.services/client/form.js?ver=2.0.1" />
<script type="text/javascript">
{`
var ss_form = {'account': 'ACCOUNT_NAME', 'formID': 'MY_FORM_ID'};
ss_form.width = '100%';
ss_form.domain = 'app-UNIQUENUMBER.marketingautomation.services';
ss_form.target_id = 'form1';
ss_form.polling = true;
`}
</script>
</Helmet>
<div id="form1"> </div>
</LayoutTemplate>
)
}
export default Preferences
The "sometimes loads sometimes not" is caused because of React's hydration, meaning that if you force a rendering (pressing F5 for example) the component is forced to render so the Helmet script is triggered.
If you use Gatsby's navigation (even React's because Gatsby extends its navigation from React) the LayoutTemplate may not be re-rendered if there's no need to.
If you are trying to use some persistent layout across your project, I'd suggest using wrapPageElement or wrapRootElement APIs.
Another hacky workaround is to force the rendering of the script function in each navigation process. This, depending on your scenario may suit you:
const addScript = url => {
const script = document.createElement("script")
script.src = url
script.async = true
document.body.appendChild(script)
}
export const onClientEntry = () => {
window.onload = () => {
addScript("https://koi-3QNLLDDY3O.marketingautomation.services/client/form.js?ver=2.0.1")
}
}
More details about onClientEntry API: https://www.gatsbyjs.com/docs/reference/config-files/gatsby-browser/#onClientEntry
Then, you can load the script using a useEffect or similar, as you wish.