【问题标题】:React - Loading external script gives me error : Failed to execute 'write' on 'Document'React - 加载外部脚本给我错误:无法在“文档”上执行“写入”
【发布时间】:2018-12-12 16:07:37
【问题描述】:

我正在尝试在我的 React 组件中间加载一个外部脚本。

import React from 'react';

class Test extends React.Component {

  componentDidMount() {
    const script = document.createElement("script");
    script.src = "http://example.com/form.js";
    this.myDiv.appendChild(script);
  }

  render() {
    return <div ref={e => (this.myDiv = e)} />;
  }
}

不幸的是,外部脚本包含document.write。因此,当我尝试加载它时它给了我一个错误:

Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

这个错误很容易理解。由于脚本是在文档被解析之后运行的,所以不能使用document.write

我有什么办法来解决这个问题?

到目前为止我做了什么:

到目前为止,我已尝试使用 Krux 的 postscribe 模块,但未能成功:

import React from 'react';

class Test extends React.Component {

  render() {
    return (
      <div>
        <div id="myDiv" />
        <script dangerouslySetInnerHTML={{
          __html: postscribe(
            "#myDiv",
            <script src="http://example.com/form.js" />
          )
        }} />
      </div>
    );
  }
} 

非常感谢任何帮助

【问题讨论】:

    标签: javascript html reactjs


    【解决方案1】:

    您可以使用“react-async-script-loader”npm 模块。

    此模块有助于组件内的延迟加载脚本。

    或者在 React-component-lifecycle 中你可以这样做:

    document.createElement('script');
            asyncScript.src = 'your script url';
            asyncScript.async = true;
            asyncScript.onload = () => {
              // The setTimeout lets us pretend that Stripe.js took a long time to load
              // Take it out of your production code!
              setTimeout(() => {
                this.setState({
                  stateVariable: **window.{your script exposed object}**
                });
              }, 500);
            };
    

    【讨论】:

      猜你喜欢
      • 2021-04-25
      • 2017-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      相关资源
      最近更新 更多