Skip to content

Instantly share code, notes, and snippets.

@jbroadice
Last active September 29, 2021 15:38
Show Gist options
  • Save jbroadice/b09d0a5541ad4fa896ab7ee14116cdb2 to your computer and use it in GitHub Desktop.
Save jbroadice/b09d0a5541ad4fa896ab7ee14116cdb2 to your computer and use it in GitHub Desktop.
unpkg.com JavaScript async module import
<!DOCTYPE html>
<html>
<head>
<title>unpkg.com dynamic import module test</title>
</head>
<body>
<script type="module">
window.module = {
set exports(module) {
window.module.modules.push(module);
},
modules: []
};
const npm = (pkg) => {
return new Promise((resolve) => {
console.log(`Loading ${pkg}`);
import(`https://unpkg.com/${pkg}`)
.then((module) => {
resolve(window.module.modules[window.module.modules.length - 1]);
});
});
}
(async () => {
console.log('Start');
const rightpad = await npm('rightpad');
console.log(rightpad('Hello', 10, '!'));
const leftpad = await npm('leftpad');
console.log(leftpad('Hello', 10, '!'));
console.log(rightpad('Hello', 10, '!'));
console.log(leftpad('Hello', 10, '!'));
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment