I'm currently trying to add a third party script to my Next.js application. The script inserts an iframe directly below the script tag. So I need precise control over where the script tag is located on the page.
I'm currently using next/script because regular script tags are preventing the iframe from rendering. However, the next/script tag seems to relocate the script based on the strategy used: Using beforeInteractive strategy inserts the script into the head. afterInteractive and lazyOnload insert it somewhere near the bottom of the page.
If I have something like the following:
<div id="script-container">
<Script id="script" async /* other attributes */ />
</div>
How would I ensure that the script remains inside the script-container div when the page loads?
Here is the somewhat hacky solution I came up with.
import React, { useRef } from 'react'
import Script from 'next/script'
export const ScriptComponent = (props) => {
const containerRef = useRef(null)
function moveScript() {
containerRef.current.appendChild(this)
}
return (
<div ref={containerRef} id="script-container">
<Script
id="script"
type="text/javascript"
src="#url"
async
onLoad={moveScript}
/>
</div>
)
}
Basically add an onLoad function that moves the script back to the container. I'm unsure how consistent this solution is overall since it depends on the script being moved before the iframe gets loaded, but it appears to be working with the script I'm using.