React JS

Load script asynchronously React JS

There are tons of node packages and libraries available to use with React JS project. There may be already some package in node for any javascript library we are wiliing to use in our project. But, by some chances, if some library is not available or we wish to use JS library instead of node package, we can load script in our project as follows.

1. Include in public/index.html

We can include script tag in the public/index.html file in our React JS project and then use it as we use in normal JS; with the window prefix.

<script src="path/to/js/library.js"></script>

Then use it in our project as follows:

window.libraryMethod()
// OR
libraryMethod()

2. Load script asynchronously

We can load JS scriptasynchronously after component has been loaded. And so loaded library gets attached to the window.

componentDidMount() {
        this.script = document.createElement("script");
        this.script.src = "/myScript.js";
        this.script.async = true;
        this.script.onload = () => this.onScriptLoad();
        document.body.appendChild(this.script);
}

onScriptLoad = () => {
// window.libraryFunction()  -- function of myScript.js
// -- OR --
// libraryFunction()
}