React - Loading external script gives me error : Failed to execute 'write' on 'Document'

问题: I am trying to load an external script in the middle of my React Component. import React from 'react'; class Test extends React.Component { componentDidMount() {...

问题:

I am trying to load an external script in the middle of my React Component.

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)} />;
  }
}

Unfortunately the external script contains document.write. Therefore it gives me an error when I try to load it :

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.

The error is quite easy to understand. As the script is run after the document as been parsed, it cannot use document.write.

What are my options to remedy this problem ?

What I did so far :

So far I have tried using Krux's postscribe module but failed to make it work :

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>
    );
  }
} 

Any help much appreciated


回答1:

you can use "react-async-script-loader" npm module.

This module helps in lazy-loading scripts within component.

Or within React-component-lifecycle you can do something like this:

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);
        };
  • 发表于 2018-07-05 15:32
  • 阅读 ( 655 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除