Skip to content

Instantly share code, notes, and snippets.

@kafene
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kafene/ec9c1fbc695f21a9ff4b to your computer and use it in GitHub Desktop.
Save kafene/ec9c1fbc695f21a9ff4b to your computer and use it in GitHub Desktop.
Using Promises to load scripts

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));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment