2

I have created a few es6 modules:

module1.js
module2.js

These modules will load content into a div with id="root"

<div id="root"></div>

document.getElementById('root').innerHTML = (results);

My question is ...

Is is possible to load modules from as onclick event for example:

<li onclick="loadModule('module1')">Load Module 1</li> //load module1.js
<li onclick="loadModule('module2')">Load Module 2</li> //load module2.js

If so, how can I do this?

  • You can use ajax. – mattdevio Jun 07 '17 at 21:17
  • 1
    See [Exporting an ECMAScript module from a – guest271314 Jun 07 '17 at 21:23
  • 1
    This doesn't really make any sense. Modules are not things which should be called from an "onclick" HTML attribute. You should be importing modules in the code where you need the functionality provided by it. If the code which handles the click event requires the use of the code in `module1`, it should import that, and that code will be loaded when needed. See https://stackoverflow.com/questions/24543074/how-does-es6-module-loading-work. – Heretic Monkey Jun 07 '17 at 21:27

2 Answers2

1

This is the best solution i found online, The previous answer adds the scripts to the inner html of the page and renders it useless (i cant click on anything)

const myModule = './myModule.js';
import(myModule)
   .then(x => x.someMethod());

Credits to @leonardobrunolima https://medium.com/@leonardobrunolima/javascript-tips-dynamically-importing-es-modules-with-import-f0093dbba8e1

sobhuxa
  • 11
  • 1
0

In the following case I am using libraries that you can get through http and then append the html with a script that points to that library you asked to be required. If the module is local, then you just use the filepath of those modules. I assume that those modules are transpiled into some sort of built folder along with the html, so you can access if from there.

function loadModule(module) {
  var script = {
    'jquery': 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js',
    'knockout': 'https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js'
  }[module];
  document.body.innerHTML += `<script src=${script} type='text/javascript'><\/script>`;
  console.log(module + ' module loaded');
}
<button onclick="loadModule('jquery')">Load jquery </button>
<button onclick="loadModule('knockout')">Load knockout.js </button>
Mμ.
  • 8,382
  • 3
  • 26
  • 36
  • The module would only be loaded after the onload event triggers, not after the innerhtml addition. Personally I would rather go for adding the script through createElement and a callback that notifies the consumer that the script is loaded succesfully – Icepickle Jun 08 '17 at 10:39