I want a dependency manager that will append script tags in order, and avoid duplicating tags with the same src. This has been an issue with the CMS we use.
I put together something like this:
const scriptLoader = new ScriptLoader({
"jquery@3.4.1": {
"attr": {
"src": "https://code.jquery.com/jquery-3.4.1.min.js",
"integrity": "sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=",
"crossOrigin": "anonymous",
},
},
"bootstrap@4.0.0": {
"attr": {
"src": "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js",
"integrity": "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl",
"crossOrigin": "anonymous",
},
"dependencies": ["jquery@3.4.1", "popper@1.12.9"],
},
});
// global js
scriptLoader.loadScript("global", {
"src": "js/global.js",
}, ["bootstrap@4.0.0", "jquery@3.4.1"]);
So when global script is loaded, it'll first load the ["bootstrap@4.0.0", "jquery@3.4.1"] dependencies by appending them as tags, before it loads/appends the global.js.
Any attempts to load global.js again will not re-append the script:
// global js - will append
scriptLoader.loadScript("global", {
"src": "js/global.js",
}, ["bootstrap@4.0.0", "jquery@3.4.1"]);
// global js - ignored, already appended/appending
scriptLoader.loadScript("global", {
"src": "js/global.js",
}, ["bootstrap@4.0.0", "jquery@3.4.1"]);
I'd looked into require.js but I'd need to re-write all my js files as require modules which I'm not that keen on.
Does anything of this sort exist already? Mine works ok-ish, but can be a little temperamental at times and would prefer something that's already out there.
As @morganney pointed out, Require.js is designed pretty much exactly for this purpose. Many popular libraries export their libraries in UMD format, which supports the AMD (Async Module Definition) logic Require.js expects.
This will simply import asynchronously all the first level libraries in your object, using just JavaScript import.
From the network debugger tab, we can observe the HTTP code 200 success:

const ScriptLoader = async (libs) => {
for (const [k] of Object.entries(libs)) {
console.log(k, libs[k].attr.src);
await import(libs[k].attr.src)
// Lib ready here
}
}
const scriptLoader = ScriptLoader({
"jquery@3.4.1": {
"attr": {
"src": "https://code.jquery.com/jquery-3.4.1.min.js",
"integrity": "sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=",
"crossOrigin": "anonymous",
},
},
"bootstrap@4.0.0": {
"attr": {
"src": "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js",
"integrity": "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl",
"crossOrigin": "anonymous",
},
"dependencies": ["jquery@3.4.1", "popper@1.12.9"],
},
});