How to load an external script and access it from the main bundle in nextJS

Solution 1:

Load the script in _document.js before next.js scripts, create _document.js in pages directory to extend the html document the way you like.

import Document, { Html, Head, Main, NextScript } from "next/document";

export default class MyDocument extends Document {
  render(){
    return (
      <Html>
        <Head>      
           /*This is loads the script in head tag of your html document*/      
           <script src="https://sdk.mercadopago.com/js/v2" strategy="beforeInteractive"/>
        </Head>

        <body>
          /*your script can also go here before loading next scripts*/
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

Solution 2:

OK, I solved this using the onLoad method available on Next/Script component. What I needed to do was to move the script inclusion to my own component and include the component there adding the onLoad props and passing a function that executed my object instance after loading it.

Here my code:

const onload = () => {
     const controller = new Controller(props);
     setController(controller);
};
const pay = () => controller.load(props.disabled);
const attrs = {onClick: pay};
if (!controller || props.disabled) attrs.disabled = true;
return(
  <>
    <section className="mercadopago-checkout-pro-component">
        <div ref={refContainer} className="cho-container">
            <button  className="btn btn-secondary" {...attrs}>
                Pay
            </button>
        </div>
    </section>
    <Script src="https://sdk.mercadopago.com/js/v2" onLoad={onload}/>
   </>
);