Created
September 3, 2020 13:21
-
-
Save andreiglingeanu/b2c64f87086fefa582e8883cb8098532 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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