React - import pure JavaScript file in async mode

4 points
Created by:

In this short article, we would like to show how to write a simple pure JavaScript file async loader for React.

Note: that kind of the tool is useful when we want to load some pure JavaScript files dynamically and use them later with React, e.g. we have $() function that was written in pure JS.

Quick solution:

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// import React from "react";
// import ReactDOM from "react-dom";

const statuses = { }; // loading, loaded, import calls chain

const loadScript= (src) => {
  	const status = statuses[src] || (statuses[src] = { });
	if (status.loaded || status.loading) {
		return status.promise;
	status.loading = true;
	status.promise = new Promise((resolve, reject) => {
       if (!document.head) {
            status.loading = false;
            reject('Load JavaScript file in web site body or after head is ready.');
        const script = document.createElement('script');
        script.addEventListener('load', () => {
            status.loaded = true;
            status.loading = false;
        script.addEventListener('error', () => {
            status.loaded = true;
            status.loading = false;
            reject('JavaScript file loading error (check script url or network connection).');
        script.async = true;
        script.src = src;
	return status.promise;

// Usage example:

const App = () => {
    React.useEffect(() => {
            .then(() => {
                $('body').css('background', 'red'); // jQuery with React
                console.log('Script loading');
            .then(() => console.log('Only waiting for the script'))
            .then(() => console.log('Only waiting for the script'))
    }, []);
    return (
      <div>Component body here...</div >

const root = document.querySelector('#root');
ReactDOM.render(<App/>, root );

Note: open Google Chrome DevTools to see the number of request for jquery.min.js file - should be only one per one site loading! 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.


React - import pure JavaScript file in async mode
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂