In my page body, I need to insert this code as the result of an AJAX call:
Loading jQuery
Wait for multiple scripts to load
The following helper loads multiple scripts only once and returns a promise:
async function cirosantilli_load_scripts(script_urls) {
function load(script_url) {
return new Promise(function(resolve, reject) {
if (cirosantilli_load_scripts.loaded.has(script_url)) {
resolve();
} else {
var script = document.createElement('script');
script.onload = resolve;
script.src = script_url
document.head.appendChild(script);
}
});
}
var promises = [];
for (const script_url of script_urls) {
promises.push(load(script_url));
}
await Promise.all(promises);
for (const script_url of script_urls) {
cirosantilli_load_scripts.loaded.add(script_url);
}
}
load_scripts.loaded = new Set();
(async () => {
await cirosantilli_load_scripts([
'https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js',
]);
// Now do stuff with those scripts.
})();
GitHub upstream: definition and usage.
Tested in Chromium 75.