Load JS modules conditionally (SystemJS)

I am currently using jspm and SystemJS to load ES6 modules. However, I would like to be able to

  • Scanning the page to certain selectors (e.g. id, data-plugin)

  • Match these selectors with their module dependencies

  • Download only those modules

My thought was to process this import data using a single entry point System.import('src/main')that has access to document. Then I could find the corresponding selectors, map these selectors to modules, and then importthose modules.

src/main will look something like this:

['d3', 'jquery'].forEach(function(dependency) {
    import dependency;
});

This is not a viable solution, as this is not valid syntax. Is there a better way to achieve dynamic module loading in this sense?

+4
source share
1 answer

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.

+3
source

All Articles