Skip to content

Instantly share code, notes, and snippets.

@andreiglingeanu
Created September 3, 2020 13:21
Show Gist options
  • Save andreiglingeanu/b2c64f87086fefa582e8883cb8098532 to your computer and use it in GitHub Desktop.
Save andreiglingeanu/b2c64f87086fefa582e8883cb8098532 to your computer and use it in GitHub Desktop.
// helpers.js
const loadSingleEntryPoint = ({
// Elements selectors
els = [],
// Execute something before the actual load of the module
beforeLoad = (el) => {},
// Perform module load & return a Promise
load,
// mount logic can be changed, if needed
mount = ({ mount, el }) => (el ? mount(el) : mount()),
// Define a condition that if not satisfied, will prevent the module from
// loading
condition,
}) => {
if (els && {}.toString.call(els) === '[object Function]') {
els = els()
}
const allEls = (Array.isArray(els) ? els : [els]).reduce(
(a, selector) => [
...a,
...(Array.isArray(selector)
? selector
: document.querySelectorAll(selector)),
],
[]
)
allEls.map(beforeLoad)
if (allEls.length === 0) {
return
}
if (
condition &&
!condition({
els,
})
) {
return
}
load().then((arg) =>
allEls.map((el) => {
mount({ ...arg, el })
})
)
}
export const handleEntryPoints = (mountEntryPoints = []) => {
document.addEventListener(
'DOMContentLoaded',
() => mountEntryPoints.map(loadSingleEntryPoint),
false
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment