Languages
[Edit]
EN

React - import pure JavaScript file in async mode

4 points
Created by:
Hayley-Mooney
677

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.');
            return;
        }
        const script = document.createElement('script');
        script.addEventListener('load', () => {
            status.loaded = true;
            status.loading = false;
            resolve();
        });
        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;
        document.head.appendChild(script);
    });
	return status.promise;
};

// Usage example:

const App = () => {
    React.useEffect(() => {
        loadScript('https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js')
            .then(() => {
                $('body').css('background', 'red'); // jQuery with React
                console.log('Script loading');
            })
            .catch(console.error);
        loadScript('https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js')
            .then(() => console.log('Only waiting for the script'))
            .catch(console.error);
        loadScript('https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js')
            .then(() => console.log('Only waiting for the script'))
            .catch(console.error);
    }, []);
    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.

ReactJS

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.

❤️💻 🙂

Join