[英]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. 我试图在我的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)} />;
}
}
Unfortunately the external script contains document.write
. 不幸的是,外部脚本包含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
. 由于脚本是在解析文档后运行的,因此无法使用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 : 到目前为止,我已尝试使用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>
);
}
}
Any help much appreciated 任何帮助非常感谢
you can use " react-async-script-loader " npm module. 你可以使用“ react-async-script-loader ”npm模块。
This module helps in lazy-loading scripts within component. 此模块有助于在组件内延迟加载脚本。
Or within React-component-lifecycle you can do something like this: 或者在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);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.