Created
April 6, 2019 04:00
-
-
Save Dakedres/5686a2681c6ebdbbf78f4d2f6a50a210 to your computer and use it in GitHub Desktop.
A light yet flexible util to load ES6 modules globally in Windows93
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(() => { | |
const { $file: file } = window | |
const openAsync = (path, type) => | |
new Promise((resolve, reject) => { | |
try { | |
const callback = (...args) => | |
resolve(args) | |
file.open(path, type, callback) | |
} catch { | |
const error = new Error('No such file.') | |
reject(error) | |
} | |
}) | |
/** | |
* Loads an ES6 module asynchronously | |
* @param {String} location The path or url to the module | |
* @returns {Promise<HTMLScriptElement>} The module's <script> tag | |
*/ | |
const load = async location => { | |
let url = location | |
if(location.startsWith('/a/')) | |
[ url ] = await openAsync(location, 'URL') | |
const script = document.createElement('script') | |
script.type = "module" | |
script.src = url | |
let promise = new Promise(resolve => { | |
script.onload = resolve | |
}) | |
document.body.appendChild(script) | |
await promise | |
return script | |
} | |
if(window) | |
Object.assign(window, { | |
/** | |
* The global alias for the load function when loaded in the browser. | |
* @namespace $load | |
*/ | |
$load: load | |
}) | |
else | |
module.exports = load | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment