EN
React - import pure JavaScript file in async mode
4
points
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!