简体   繁体   中英

How to get response from external js which is not in npm (node modules)

How to get response from external js which is not in npm (node modules).

Here i need to call some functions from react file and expecting the return value from external js file to be utilized in my component

Appending an external script on componentDidMount() is an option.

componentDidMount() {
  const script = document.createElement("script");
  script.src = "path/to/your/file.js";
  script.async = true;
  script.onload = () => this.externalScriptLoaded();
  document.body.appendChild(script);
}

Then inside externalScriptLoaded , you can access functions in your external script using window object.

externalScriptLoaded() {
  window.externaljs.someFunction(); // replace externaljs
}

You just need to make sure that the external module is loaded before you call any function from that module. It is okay to do unless the external js manipulates the DOM.

Edit: you can load the external js using <script> tag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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