Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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
You can’t perform that action at this time.