I want to load some script files in Helmet
tag using Gatsby.js , the script files are something like this:
<script type="text/javascript">
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('consent', 'default', {
ad_storage: 'denied',
analytics_storage: 'denied',
wait_for_update: 1500,
});
gtag('set', 'ads_data_redaction', true);
</script>
This is my SEO component :
<Helmet>
<title>{metaTitle}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script id="CookieConsent" src="https://policy.app.cookieinformation.com/uc.js" data-culture="EN" type="text/javascript"></script>
<script async src="https://www.googletagmanager.com/gtag/js?id=321012880"></script>
<script type="text/javascript">
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('consent', 'default', {
ad_storage: 'denied',
analytics_storage: 'denied',
wait_for_update: 1500,
});
gtag('set', 'ads_data_redaction', true);
</script>
</Helmet>
when I use this directly inside the Helmet
tag , this will cause an error , better said , the script code will not be read
any idea how to solve this ? or is there any alternative to load script files in Gatsby ?
Thanks
You can use Gatsby's Script API: https://www.gatsbyjs.com/docs/reference/built-in-components/gatsby-script/
Your example code then would look like this:
import { Script } from "gatsby"
<Script id="gtag-config">
{`
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('consent', 'default', {
ad_storage: 'denied',
analytics_storage: 'denied',
wait_for_update: 1500,
});
gtag('set', 'ads_data_redaction', true);
`}
</Script>
Then use this snippet in whichever React component you want. Please note that you'll need to add an id
to the component for inline scripts (see https://www.gatsbyjs.com/docs/reference/built-in-components/gatsby-script/#inline-scripts)