Skip to content

Instantly share code, notes, and snippets.

@walaura
Created September 26, 2017 13:08
Show Gist options
  • Save walaura/03f39945e102ee179dc8cc712da216cb to your computer and use it in GitHub Desktop.
Save walaura/03f39945e102ee179dc8cc712da216cb to your computer and use it in GitHub Desktop.
Cheap and easy js module loader

okay so basically this will scan for elements with a css class and attach the module to them, this pattern is v good because your module code is separate from binding, which means you can scale it up to ajax sites.

doing async imports is totes optional but it lets you have a single list of modules

const modules = [
'whatevers',
'trigger-modal',
'trigger-popover',
'header',
]
modules.map(selector=>{
const $elements = document.querySelectorAll('.'+selector);
/*IE9 doesn't do .forEach() :( */
for (i = 0; i < $elements.length; ++i) {
let $element = $elements[i];
System.import('./module-'+selector).then(Module=>{
new Module.default($element).apply()
})
}
})
export default class base {
constructor($element) {
this.$element = $element;
}
apply() {
/*
i kinda like this second
constructor pattern because it lets
you change the # of parameters for the
constructor later on
*/
}
}
import base from './module-base';
export default class header extends base {
apply() {
console.log(this.$element);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment