【问题标题】:How to load script dynamically before any other scripts in nextjs _app.js?如何在 nextjs _app.js 中的任何其他脚本之前动态加载脚本?
【发布时间】:2022-09-24 13:27:38
【问题描述】:

我有一个 nextjs 项目。我想为我的域实施 oneTrust CMP 解决方案。我需要在 _app.js 文件中的任何其他脚本之前放置 oneTrust 脚本,并且我想检查子域是否为 \'X\' 然后我不想加载脚本。我已经使用 useEffect 实现了这个。我最初设置了 load = true,并且在域 \'X\' 的 useEffect 中我设置了 load = false。在代码中,如果负载设置为 true,我会加载 sciprts。但是对于域 \'X\',我的脚本仍在加载中。

我的代码:

function MyApp({ Component, pageProps }) {
   const [load, setLoad] = useState(true);
   useEffect(() => {
    if (window != undefined) {
       // console.log(window.location);
       const paths = window.location.host;
       if (paths.includes(\"X\")) {
         setLoad(false);
       }
     }
   }, []);
  return (
    <Fragment>
      <Head>
        
      </Head>
      {load ? (
        <>
          <Script
            strategy=\"beforeInteractive\"
            src=\"src\"
            type=\"text/javascript\"
            charSet=\"UTF-8\"
            data-domain-script=\"some-id\"
          ></Script>
          <Script
            id=\"test\"
            strategy=\"beforeInteractive\"
            type=\"text/javascript\"
            dangerouslySetInnerHTML={{
              __html: `
           js code
      `,
            }}
          />
        </>
      ) : (
        \"\"
      )}

      Some other scripts....
      <Component {...pageProps} />
    </Fragment>
  );
}

我在这里做错了什么?并且我的 oneTrust 脚本会以这种方式在其他脚本之前执行吗?

    标签: react-hooks next.js one-trust


    【解决方案1】:

    对于那些有同样问题的人,我解决了这个问题。您可以将 getInitialProps 添加到您的 _app.js 文件中,并在那里添加您的主机检测代码。

    rest of the _app.js code
    MyApp.getInitalProps = async(context)=>{
    const url = context.ctx.req.headers.host;
    // pass the url data to your component
      return { data: url };
    }
    export default MyApp
    

    【讨论】:

      猜你喜欢
      • 2018-06-29
      • 2015-03-28
      • 1970-01-01
      • 2022-08-23
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      • 2023-03-03
      相关资源
      最近更新 更多