The usual importsyntax cannot be used to conditionally load modules, as you have already seen. To get around this, we can use the software API provided System. You are already familiar with this API because you use it in System.import('src/main');.
To conditionally load modules, instead of using a keyword, importyou just need to continue using the method System.import.
An example of this:
index.html
<!DOCTYPE html>
<html>
<head>
<script src="jspm_packages/system.js"></script>
<script src="config.js"></script>
</head>
<body>
<div id='one'>One</div>
<div>Two</div>
<script>
System.import('main');
</script>
</body>
</html>
main.js
const map = {
'#one': 'one',
'#two': 'two'
};
for (let selector in map) {
if (document.querySelector(selector)) {
System.import(map[selector]);
}
}
one.js
window.HAS_ONE = true;
two.js
window.HAS_TWO = true;
This example will be defined window.HAS_ONEbut window.HAS_TWOwill remain undefined.
source
share