Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!