Skip to content

Instantly share code, notes, and snippets.

@honewatson
Last active April 21, 2018 03:50
Show Gist options
  • Save honewatson/2edc62d1e083dd80a5b157bbc6052db1 to your computer and use it in GitHub Desktop.
Save honewatson/2edc62d1e083dd80a5b157bbc6052db1 to your computer and use it in GitHub Desktop.
Loader JS Dynamic Loading
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Index</title>
</head>
<body>
<div id="ROOT"></div>
<script>
(function(window){
const ready = (test, fn) => {
const result = test();
if(!result) {
setTimeout(() => ready(test, fn), 1);
}
else {
fn(result);
}
}
const __loader = (registry = {}, loading = {}) => (fn, ...items) => {
items.forEach(item => {
if(typeof loading[item] === 'undefined') {
loading[item] = true;
import(`./${item}.js`).then(module => {
registry[item] = module;
})
}
});
ready(
() => items.every(item => !!registry[item]) ? registry : null,
(registry) => fn(registry)
)
}
window.__loader = __loader;
})(window);
(function(window){
window.loader = __loader();
})(window);
(function(loader) {
loader((r) => {
console.log(r.test.hello())
console.log(r.test1.hello())
}, 'test', 'test1')
})(window.loader);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment