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:
xxxxxxxxxx
1
//Note: Uncomment import lines during working with JSX Compiler.
2
// import React from "react";
3
// import ReactDOM from "react-dom";
4
5
const statuses = { }; // loading, loaded, import calls chain
6
7
const loadScript= (src) => {
8
const status = statuses[src] || (statuses[src] = { });
9
if (status.loaded || status.loading) {
10
return status.promise;
11
}
12
status.loading = true;
13
status.promise = new Promise((resolve, reject) => {
14
if (!document.head) {
15
status.loading = false;
16
reject('Load JavaScript file in web site body or after head is ready.');
17
return;
18
}
19
const script = document.createElement('script');
20
script.addEventListener('load', () => {
21
status.loaded = true;
22
status.loading = false;
23
resolve();
24
});
25
script.addEventListener('error', () => {
26
status.loaded = true;
27
status.loading = false;
28
reject('JavaScript file loading error (check script url or network connection).');
29
});
30
script.async = true;
31
script.src = src;
32
document.head.appendChild(script);
33
});
34
return status.promise;
35
};
36
37
// Usage example:
38
39
const App = () => {
40
React.useEffect(() => {
41
loadScript('https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js')
42
.then(() => {
43
$('body').css('background', 'red'); // jQuery with React
44
console.log('Script loading');
45
})
46
.catch(console.error);
47
loadScript('https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js')
48
.then(() => console.log('Only waiting for the script'))
49
.catch(console.error);
50
loadScript('https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js')
51
.then(() => console.log('Only waiting for the script'))
52
.catch(console.error);
53
}, []);
54
return (
55
<div>Component body here...</div >
56
);
57
}
58
59
const root = document.querySelector('#root');
60
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!