How to precisely control where script tag is inserted using Next Script

Solution 1:

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.