简体   繁体   中英

Include external .js file in ReactJs web project

As the external.js file url belongs to the customer, so I can't share that, I need to include the external js file, and call the function from that external js file. I have seen some solution like:

const script = document.createElement('script');
script.src = url;   //(This is external js url)
script.async = true;
document.body.appendChild(script);

But it is not working for me, or may be I don't know how it works

Assume this is the external sample code:

Sample code to call locally, if we manually download the file and import

  let conn = demo("url", false)
  conn.login("username", "myPassword")

How to do same above call after including in the reactjs

 export default function demo (end, sec) {  
    const login = (user, password) => {
            console.log(" sending login message")

    }
   
    const logout = async (user) => {
                    console.log(" sending logout message")
    }


    /*
     * Expose these methods to the client
     */
    return { login, logout }
}

You will need to append your snippet in one lifecycle method like componentDidMount so React can mount it (or load) whenever you component has been mounted. Once is done, you could call the custom method.

If you use class component:

class MyComponent extends Component {

  componentDidMount() {
    const script = document.createElement('script');
    script.src = url;   //(This is external js url)
    script.async = true;
    document.body.appendChild(script);
  }

  render() { 
    return null;
  }
}

Or if you use functional component with hooks

const MyComponent = () => {
  useEffect(() => {
    const script = document.createElement('script');
    script.src = url;   //(This is external js url)
    script.async = true;
    document.body.appendChild(script);
  }, [])
}

To add the external js, there are two option

  1. Create an custom script and add the js file asynchronously.
  2. Use third party node module

Below are Script-

const addExternalJs = () => {
   const script = document.createElement("script");
  script.src = "/<path1>/<path2>/yourJSFile.js";
  script.async = true;
  script.onload = () => this.scriptLoaded();

  document.body.appendChild(script);
}
  1. Functional Based Component

    useEffect(() => { addExternalJs(); }, []);

  2. Class Based Component

    componentDidMount() { addExternalJs(); }

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