javascriptnext.jsembedding

Updated: How can I insert a script at a specific position in the page of a NextJS app?


I am trying to get a script embedding onto my next.js application, however it is at the end of the page, instead of where I place it.

I already took the solution mentioned in How to precisely control where script tag is inserted using Next Script, but the issue still persists. I also tried to embed it with the application script method described here https://nextjs.org/docs/basic-features/script, but I get the same result.

My helloworld.tsx in pages looks like this:

import React, { useRef } from 'react'
import Script from 'next/script'

export const HelloWorld = () => {

    const containerRef = useRef(null)

    function moveScript() {
        containerRef.current.appendChild(this)
    }

    return (
        <>
            <p>This goes before the embedding</p>
            <div ref={containerRef} id="script-container">
                <Script strategy="lazyOnload" id="asciicast-aMFGH8jU7O7uo94YZyWJEZtnO" type="text/javascript" src="https://asciinema.org/a/aMFGH8jU7O7uo94YZyWJEZtnO.js" async onLoad={moveScript}/>
            </div>
            <p>This goes after the embedding <br /></p>
        </>
    );
};
export default HelloWorld;

On the resulting page the embedding is at the bottom of the page, however I expect it to be between the two paragraph.

What am I missing?


Solution

  • Why don't you use an useEffect to load the script, and then append it? Since useEffect runs after the render of the component, you could either:

    [1] use it to load the script in it (assuring that the script load goes after the component rendering), or

    [2] use it afterwards to move (append) the script to the specific ref. I can't test your code right now, but I'm pretty sure that might help you solve the problem you're having.