首页 > 解决方案 > React - 加载外部脚本给我错误:无法在“文档”上执行“写入”

问题描述

我正在尝试在我的 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>
    );
  }
} 

非常感谢任何帮助

标签: javascripthtmlreactjs

解决方案


你可以使用“ 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);
        };

推荐阅读