I had a few of scripts I want to load in my userscript before executing it. After some head scratching and messing around with Promises it turns out it's quite easy. This way there's no need to require a larger module loader and other dependencies, which can be a pain to work with when writing userscripts.
(function load(scripts) {
// Wait for DOMContentLoaded/window.onload
if (document.readyState !== "interactive" && document.readyState !== "complete") {
document.addEventListener("DOMContentLoaded", load.bind(null, scripts));
return;
}
// Once all of the promises in the array returned by `scripts.map`
// have resolved, the `then` method below will be called.
return Promise.all(scripts.map(src => new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = src;
script.type = "application/javascript;version=1.8";
script.onload = resolve;
script.onerror = script.onabort = reject;
document.querySelector("head").appendChild(script);
})));
})([
"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.3.0/codemirror.js",
"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.3.0/mode/php/php.js",
]).then(function () {
console.info("resolved", arguments);
console.info(CodeMirror);
}).catch(console.error.bind(console));