Reputation: 1494
I have a NextJS app and the page structure loosely looks like this:
<Head>
<Navigation>
<Page>
<Footer>
I have a DTM script that I need to load in the <Head>
component and then there are tags that I am firing in the <Page>
component. But the problem is, the tags in <Page>
starts firing before the DTM script get's loaded onto the page.
So, is there a way to let the DTM script in the <Head>
tag load first before the <Page>
component loads? I was looking to use "componentwillmount" but it's being deprecated.
Can someone please advice how can I tackle this issue?
Upvotes: 5
Views: 18875
Reputation: 11593
next.js offers onLoad
, which triggers once the external script is loaded:
<Script src="https://example.org/script.js"
onLoad={() => {
console.log('script has loaded')
}
/>
Upvotes: 2
Reputation: 193
You can use Head
in any components by Nextjs.
How about you add Head
in Page
and put <script/>
inside
Upvotes: -1
Reputation: 2328
You could listen to the script load event from your <Page>
component using vanilla javascript.
in your custom _document:
<script id="dtm" src="dtm.js" />
then in the <Page>
component:
document.getElementById("dtm").addEventListener('load', () => {
// DTM is loaded
})
Upvotes: 6