简体   繁体   English

如何将异步脚本添加到 React

[英]How to add async script to React

I need to add a div & async script at the bottom of the page in my react application.我需要在我的react应用程序的页面底部添加一个div & async script

1st Try:第一次尝试:

  ...
  ...
  render() {
    return (
      <div>
        <HeaderComponent />
        <Notifications />
        {children}
        <FooterComponent />
        <div
          className="cc-banner-embed"
          data-config="YmFja2MGVUJhY2tncm91bmQ9dHJ1ZQ==">
          <script async src="https://banner.crowdcube.com/embed.js"></script>
        </div>
      </div>
    );
  }

2nd Try:第二次尝试:

  ...

  // use lifecycle method to load script
  componentDidMount() {
    const s = document.createElement("script");
    s.type = "text/javascript";
    s.async = true;
    s.src = "https://banner.crowdcube.com/embed.js";
    this.instance.appendChild(s);
  }

  render() {
    return (
      <div>
        <HeaderComponent />
        <Notifications />
        {children}
        <FooterComponent />
        <div
          className="cc-banner-embed"
          data-config="YmFja2MGVUJhY2tncm91bmQ9dHJ1ZQ=="
          ref={el => (this.instance = el)}>
        </div>
      </div>
    );
  }

Unfortunately, both of these didn't work.不幸的是,这两种方法都不起作用。 How do I get this script file to load async.我如何让这个脚本文件加载异步。

EDIT: My code was actually correct, however, in this case, the browser for some reason wasnt displaying it (cookie issue maybe).编辑:我的代码实际上是正确的,但是,在这种情况下,浏览器由于某种原因没有显示它(可能是 cookie 问题)。 Going in incognito did the trick.隐身进入就行了。 Thank you.谢谢你。

You can try this to load your script to your react app您可以尝试将您的脚本加载到您的反应应用程序

  componentDidMount() {
    const head = document.querySelector('head');
    const script = document.createElement('script');
    script.setAttribute('async',true);
    script.setAttribute('src', 'https://banner.crowdcube.com/embed.js');
    head.appendChild(script);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM