Wait for external script to load before the React component

Viewed 10243

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?

2 Answers

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
})

You can use Head in any components by Nextjs. How about you add Head in Page and put <script/> inside

Related